Memoization of promise-based function

前端 未结 5 674
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:26

    Memoization and promises aren't obvious. Even worst with the new async / await syntax.

    in order to get somewhint like that working:

    memoize(async () => 42) 
    

    or

    const whatsTheAnswerToLifeTheUniverseAndEverything = () => 42
    memoize(whatsTheAnswerToLifeTheUniverseAndEverything) 
    

    You need a memoize function or library which supports promises and async syntax. A couple of them: - https://github.com/aboutlo/async-memo-ize (Disclosure: I did this lib) - https://github.com/medikoo/memoizee

    Notice: Memoization is a cool technique however you save CPU resources at the cost of a memory consumption. You should take care how those libraries approach this issue at scale ;)

提交回复
热议问题