且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建一个函数返回一个现有的promise而不是新的promise?

更新时间:2023-12-02 21:48:04

您需要 memoise promise ,而不是它解析的值。记忆与承诺一样正常作为结果值。

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);

(注意 notSoRandomAsyncNumberPlusOne randomAsyncNumber()在第一次调用,而不是 notSoRandomAsyncNumber()

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