Memoization of promise-based function

前端 未结 5 686
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:07

    As @Bergi, and @BenjaminGruenbaum have pointed out, yes memoization is fine here, but it should be pointed out that your foo function is doing nothing useful and is actually introducing bugs (see: deferred antipattern).

    If all you want is to memoize the result of doSomethingAsync, then you can cut out the middle-man:

    var fooMemoized = memoize(doSomethingAsync);
    

    Or if you were actually oversimplifying and foo() is passing arguments to doSomethingAsync, then you can still reduce it to one line:

    function foo() {
        return doSomethingAsync(argument1, argument2, etc.);
    }
    var fooMemoized = memoize(foo);
    

    Or if you don't actually plan to use foo(), you can do:

    var fooMemoized = memoize(function () {
        return doSomethingAsync(argument1, argument2, etc.);
    });
    

提交回复
热议问题