Promise.resolve 与解决 [英] Promise.resolve vs resolve
问题描述
我有这个代码:
var promise1 = new Promise(function(resolve, reject) {
setTimeout(() => {
console.warn('Elo');
resolve('First response');
},
1000);
})
promise1
.then((resp) => {
console.warn('First then!');
});
它会在一秒钟后解析 promise 到 then 和 console.warning 'First then!'.
And It resolves promise after one second going to then and console.warning 'First then!'.
但是当我换行时:
resolve('First response');
为了
Promise.resolve('First response');
这行不通.知道为什么吗?
It won't work. Some idea why ?
也试过了
return Promise.resolve('First response');
但它也不起作用.我不知道为什么.
But it also doesn't work. I don't know why.
你能帮我理解吗?
推荐答案
new Promise
构造函数将特定函数传递到您的回调中,该函数成为您的 resolve
参数.该承诺(您使用 new Promise
在那里构建的承诺)只能通过调用特定的 resolve
函数来解决.
The new Promise
constructor passes a specific function into your callback, which becomes your resolve
parameter. That promise (the one you're constructing there with new Promise
) can only be resolved by calling that specific resolve
function.
Promise.resolve
只是创建一个新的预解析"承诺.它不会解析任何现有的承诺(也无法知道它应该解决哪个承诺).
Promise.resolve
simply creates a new "pre-resolved" promise. It does not resolve any existing promise (nor would it have any way of knowing which promise it's supposed to resolve).
这篇关于Promise.resolve 与解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!