[英]Why does then return a new promise instead of returning promise returned by onFulfilled
I was wondering why, if then()'s onFulfilled handler returns a promise p2, how come then() returns a new promise p3 instead of just returning p2? 我想知道为什么,如果then()的onFulfilled处理函数返回一个承诺p2,那么then()为什么返回一个新的承诺p3而不是仅仅返回p2?
Example: 例:
let p1 = new Promise(function(resolve, reject) {
resolve(42);
});
let p2 = new Promise(function(resolve, reject) {
resolve(43);
});
let p3 = p1.then(function(value) {
// first fulfillment handler
console.log(value); // 42
return p2;
});
p3.then(function(value) {
// second fulfillment handler
console.log(value); // 43
});
Why doesn't p1.then() just return p2 instead of making a new promise p3? 为什么p1.then()不只是返回p2而不是做出新的承诺p3? It would have the same result.
它会有相同的结果。
Because then()
returns a value immediately , before your callback even runs. 因为
then()
立即返回一个值,甚至在您的回调运行之前。
It cannot possibly know what you're going to return. 它可能无法知道您将要返回什么。
Simply because p3
is created and returned before the onFulfilled
callback will run - then
callbacks are always asynchronous. 很简单,因为
p3
创建和之前返回onFulfilled
回调将运行- then
回调总是异步的。 It cannot know yet what value will be returned in the future, so it creates a promise for it. 它尚不知道将来会返回什么价值,因此为它创造了希望。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.