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

萝らか妹 提交于 2019-11-28 14:17:18
Bergi

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

Try the new variable approach suggested. Promises are designed to be single-shot, so it depends on the implementation. What you are trying to do is more in the arena of events or reactivex. If you are using jquery then you can use their event scheme. A cleaner one is available on the nodejs site. Since it does not require anything else it runs in the browser. rxjs is the cream of the stream processing crop, but it is a big library and requires some learning. Worth it - since the same knowledge is useful client and server in many languages. You can even set up a stream from a promise - among many other ways.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!