3 回答

TA贡献1719条经验 获得超6个赞
当您有一个Promise时,可以将任意数量的Promises链接到其上.then。例如
const p = Promise.resolve();
p.then(() => console.log('then 1');
p.then(() => console.log('then 2');
表示在解决时p有两个从其分支的Promises:1和2(除了Promisep本身)。
p
/ \
/ \
1 2
您在第一个代码中正在做什么
let p = new Promise((resolve, reject) => {
resolve("Hello world")
});
p.then(data => {
console.log("second");
}).then(data => {
console.log("third")
})
return p;
就好像
"Hello world" = <Promise you return>
|
|
|
second
|
|
|
third = <unused Promise expression that the then chain resolves to>
您有两个分支:返回的Promise在Hello world运行时解析,而不是在third运行时解析。
另一方面,当您.then多次在Promise上调用时,整个表达式将计算为Promise,该Promise在最终.then运行时解析:
let p = new Promise((resolve, reject) => {
resolve("Hello world")
}).then(data => {
console.log("Hello world a second time!");
}).then(data => {
console.log("Hello world a third time")
})
return p;
就好像
"Hello world"
|
|
'Hello second'
|
|
'Hello third' = <Promise you return>
返回的Promise是Hello third运行后立即解决的Promise 。

TA贡献2041条经验 获得超4个赞
而不是返回p单独的版本,而是返回p.then()链。最后一个将添加到该链的末尾,而不是创建两个不同的链
then()返回通过任何退货或undefined如果没有退货解决的新承诺
const query = () => {
let p = new Promise((resolve, reject) => {
resolve("Hello world")
});
return p.then(data => {
// from `resolve()`
console.log('Then 1: ', data)
// return to next then()
return ("Hello world a second time!");
}).then(data => {
// from previous then()
console.log('Then 2: ', data)
// return to next then()
return ("Hello world a third time")
});
}
query().then(res => console.log('Final: ', res))
添加回答
举报