我之前问过的一个问题,和这个问题的标题完全一样,答案是“你不应该用它,用它代替它”,我想知道它能做什么,而不是我还能做什么,这是关于理解而不是简单的复制粘贴。
我的问题很简单,这三种方法在创造承诺时有什么区别?
const API = (item, fail) =>
new Promise((resolve, reject) => {
if (fail) reject(item + ' ...with an error');
setTimeout(() => resolve(item), 1000);
});
(async () => {
const pro1 = Promise.resolve(API('I am inside resolve'));
const pro2 = Promise.resolve(API('I am inside resolve', true));
const pro3 = Promise.resolve().then(() => API('I am thenable'));
const pro4 = Promise.resolve().then(() => API('I am thenable', true));
const pro5 = new Promise((resolve) => resolve(API('I am a new promise')));
const pro6 = new Promise((resolve) => resolve(API('I am a new promise', true)));
const store = [pro1, pro2, pro3, pro4, pro5, pro6];
const results = await Promise.allSettled(store);
for (const { status, value, reason } of results) {
if (status === 'fulfilled') console.log(value)
else console.log(reason)
}
})();
发布于 2021-10-11 17:04:05
不同之处在于要做的工作。虽然所有这些方法都是有效的,但它们具有不同的成本和可预测性。
Promise.resolve()生成单个已解析的允诺实例,并根据提供给调用JS引擎的值对其进行优化。它使所有的工作在一个调用JS引擎的底层代码时完成(通常是C++,但可以是Java或WASM)。所以这永远是最好的选择。Promise.resolve().then(() => API(/*...*/))产生了几个承诺实例:一个在Promise.resolve()上,另一个在.then()调用时。它还分配了更多的内存,并在JS和引擎之间进行了几次(3或更多)冗余跳转。它很难优化,需要执行密集的启发式来确定这个调用是可优化的。这是最糟糕的选择。new Promise((resolve) => resolve(API(/* ... */))分配一个函数和一个承诺实例,并在JS和引擎之间进行两次跳转。由于JS的特性,优化这个调用是很困难的。发布于 2021-10-11 16:59:11
Promise.resolve().then() 在您的示例中,then()并没有什么区别,因为您只需要解析承诺并获取其数据。
then()通常用于连锁承诺,举个例子:
Promise.resolve('foo')
// 1. Receive "foo", concatenate "bar" to it, and resolve that to the next then
.then(function(string) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
string += 'bar';
resolve(string);
}, 1);
});
})
// 2. receive "foobar", register a callback function to work on that string
// and print it to the console, but not before returning the unworked on
// string to the next then
.then(function(string) {
setTimeout(function() {
string += 'baz';
console.log(string); // foobarbaz
}, 1)
return string;
})在这里,我们将多个承诺( then() )与以前解决的承诺联系在一起,同时维护来自第一个解析的原始数据,不过在本例中,我们使用每个新的承诺对其进行修改。
您可以阅读更多关于承诺和链接这里的内容。
https://stackoverflow.com/questions/69529695
复制相似问题