Memoization of promise-based function

前端 未结 5 685
Happy的楠姐
Happy的楠姐 2020-12-04 02:01

How can I memoize a promise-based function?

Would straightforward memoization of the function suffice?

function foo() {
    return new Promise((reso         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 02:34

    For promises simple sync memoize will not be good, because in most of cases you will not wish to memoize errors (rejected promises).

    I did a simple library for common needs: https://github.com/nodeca/promise-memoize

    1. It memoize Promise-based function, except errors by default
    2. You can set expiration time for result
    3. If you need, you can remember (and set expiration time) for errors too.
    4. Data can be prefetched prior to expire, to never leave cache in cold state.

    Pseudo code:

    let db = require('mongoose').createConnection('mongodb://localhost/forum');
    
    function lastPosts(limit) {
      return db.model('Post').find()
        .limit(limit).orderBy('-_id').lean(true).exec(); // <- Promise (thenable)
    }
    
    let cachedLastPosts = require('promise-memoize')(lastPosts, { maxAge: 60000 });
    
    // Later...
    cachedLastPosts(10).then(posts => console.log(posts));
    

提交回复
热议问题