如何创建一个返回现有承诺而不是新承诺的函数? [英] How to create a function that returns an existing promise instead of new promise?
问题描述
JavaScript/Promise 专家,
JavaScript/Promise experts,
我希望你能帮助我,因为我不明白如何创建一个返回现有承诺而不是新承诺的函数.我做了大量的研究,但所有示例在每次调用该函数时都会返回一个新的 promise.
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. I have done a lot of research, but all examples return a new promise every time the function is called.
假设我有一个函数需要一些时间来处理并在每次调用时生成不同的结果.当我使用新的 promise 方法时,我仍然需要等待每次完成,如果我回忆起函数,我不会得到相同的值.
Assume I have a function that takes some time to process and generates a different result every time it is being called. When I use the new promise method then I still need to wait to complete every time and I don't get the same value if I recall the function.
我已经包含了我创建的可按预期工作的概念证明(除非我忽略了某些东西).我认为这个解决方案"很难看,因为我需要将变量移动到更高的范围,并且每次调用函数时我仍然需要创建一个新的承诺.
I have included proof of concept I have created that works as desired (unless I have overlooked something). I think this "solution" is ugly, because I need to move variables to a higher scope and I still need to create a new promise every time the function is called.
我此时的假设;为了制作这个漂亮的代码,该函数需要返回一个现有的承诺而不是一个新的承诺,但如果其他解决方案提供相同的功能和更好的代码,那么请告诉我.原生 ES6 优先.
My assumption at this moment; to make this nice code the function needs to return an existing promise instead of a new one, but if other solutions provide the same functionality and nicer code then please let me know. Native ES6 is preferred.
谢谢!
-
'use strict';
var p;
var q;
var randomNumber = function() {
return new Promise(function(resolve) {
console.log(`p: ${p}`);
if (typeof p === 'undefined') {
setTimeout(function() {
p = Math.random();
resolve(p);
}, 1000);
} else {
resolve(p);
}
});
};
var randomNumberPlusOne = function() {
return new Promise(function(resolve) {
console.log(`q: ${q}`);
if (typeof q === 'undefined') {
randomNumber()
.then(function(p) {
q = p + 1;
resolve(q);
});
} else {
resolve(q);
}
});
};
var showResult = function(result) {
console.log();
console.log(`r: ${result}`);
};
randomNumber()
.then(showResult);
randomNumber()
.then(randomNumberPlusOne)
.then(showResult);
randomNumberPlusOne()
.then(showResult);
setTimeout(function() {
console.log();
console.log('setTimeout:');
console.log();
randomNumber()
.then(showResult);
randomNumber()
.then(randomNumberPlusOne)
.then(showResult);
randomNumberPlusOne()
.then(showResult);
}, 2000);
-(以下代码基于来自 Bergi 的反馈;
- (code below is based on the feedback from Bergi;
'use strict';
var randomNumber = (function() {
var p = null;
return function() {
console.log('p:');
console.log(p);
console.log();
if (!p) {
p = new Promise(function(resolve) {
setTimeout(function() {
resolve(Math.random());
}, 1000);
});
}
return p;
};
})();
var randomNumberPlusOne = (function() {
var q = null;
return function() {
console.log('q:');
console.log(q);
console.log();
if (!q) {
q = randomNumber()
.then(function(p) {
return p + 1;
});
}
return q;
};
})();
var showResult = function(result) {
console.log(`r: ${result}`);
console.log();
};
randomNumber()
.then(showResult);
randomNumber()
.then(randomNumberPlusOne)
.then(showResult);
randomNumberPlusOne()
.then(showResult);
setTimeout(function() {
console.log();
console.log('setTimeout:');
console.log();
randomNumber()
.then(showResult);
randomNumber()
.then(randomNumberPlusOne)
.then(showResult);
randomNumberPlusOne()
.then(showResult);
}, 2000);
推荐答案
你会想要memoise promise,而不是它解析的值.Memoisation 适用于承诺作为结果值.
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()
)
这篇关于如何创建一个返回现有承诺而不是新承诺的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!