[英]Promise.resolve vs resolve
I have this code:我有这个代码:
var promise1 = new Promise(function(resolve, reject) {
setTimeout(() => {
console.warn('Elo');
resolve('First response');
},
1000);
})
promise1
.then((resp) => {
console.warn('First then!');
});
And It resolves promise after one second going to then and console.warning 'First then!'.它在一秒钟后解决承诺,然后和 console.warning 'First then!'。
But when I change line:但是当我换行时:
resolve('First response');
for对于
Promise.resolve('First response');
It won't work.它不会工作。 Some idea why ?
为什么?
Also tried也试过
return Promise.resolve('First response');
But it also doesn't work.但它也不起作用。 I don't know why.
我不知道为什么。
Can you help me understand it?你能帮我理解吗?
The new Promise
constructor passes a specific function into your callback, which becomes your resolve
parameter. new Promise
构造函数将特定函数传递到您的回调中,该函数成为您的resolve
参数。 That promise (the one you're constructing there with new Promise
) can only be resolved by calling that specific resolve
function.该承诺(您在那里使用
new Promise
构建的new Promise
)只能通过调用该特定的resolve
函数来resolve
。
Promise.resolve
simply creates a new "pre-resolved" promise. Promise.resolve
只是创建一个新的“预解析”承诺。 It does not resolve any existing promise (nor would it have any way of knowing which promise it's supposed to resolve).它不解决任何现有的承诺(它也无法知道它应该解决哪个承诺)。
Another way to think about it is:另一种思考方式是:
Resolve === resolveCallback === first argument provided to your Promise callback Promise.resolve === a function to returns a new Promise
Resolve === resolveCallback === 提供给你的 Promise 回调的第一个参数 Promise.resolve === 一个返回
new Promise
的函数
These two are functional equivalents:这两个是功能等效的:
`const foo = Promise.resolve('First response').then( /* ... */ );`
`const bar = new Promise(function(resolveCallback, rejectCallback) {
resolveCallback('First response');
}).then( /* ... */ );`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.