How to create a function that returns an existing promise instead of new promise?

后端 未结 2 1463
刺人心
刺人心 2020-12-12 02:34

JavaScript/Promise experts,

I hope you can help me, because I don\'t understand how I can create a function that returns an existing promise instead of a new promise

2条回答
  •  一向
    一向 (楼主)
    2020-12-12 02:52

    You'll want to memoise the promise, not the value that it resolves with. Memoisation works fine with promises as result values.

    var p = null;
    function notSoRandomAsyncNumber() {
      if (!p)
        p = new Promise(function(resolve) {
          setTimeout(function() {
            resolve(Math.random());
          }, 1000);
        });
      return p;
    }
    

    Or, abstracted into a helper function:

    function memoize(fn) {
      var cache = null;
      return function memoized(args) {
        if (fn) {
          cache = fn.apply(this, arguments);
          fn = null;
        }
        return cache;
      };
    }
    function randomAsyncNumber() {
      return new Promise(res => {
        setTimeout(() => resolve(Math.random()), 1000);
      });
    }
    function randomAsyncNumberPlusOne() {
      return randomAsyncNumber().then(n => n+1);
    }
    var notSoRandomAsyncNumber = memoize(randomAsyncNumber);
    var notSoRandomAsyncNumberPlusOne = memoize(randomAsyncNumberPlusOne);
    

    (notice that notSoRandomAsyncNumberPlusOne still will create a randomAsyncNumber() on the first call, not a notSoRandomAsyncNumber())

提交回复
热议问题