gpt4 book ai didi

javascript - JS ES6 promise 链接

转载 作者:数据小太阳 更新时间:2023-10-29 04:00:12 26 4
gpt4 key购买 nike

我正在尝试学习如何使用 promises,但在理解链接时遇到了问题。我假设使用这段代码,两个 promise 都会运行。然后,当我调用 test.then() 时,它应该知道测试已解析并将解析数据传递给 then()。

一旦该函数完成,它就会进入下一个 then(),用 test2 promise 重复相同的过程。

但是,我只能让它打印出第一个 promise 结果,而不是第二个。知道这里缺少什么吗?

var test = new Promise(function(resolve, reject){
resolve('done1');
});

var test2 = new Promise(function(resolve, reject){
resolve('done2');
});

test
.then(function(data) {
console.log(data);
})
.then(test2)
.then(function(data) {
console.log(data);
});

最佳答案

您的第一个 .then 调用返回 undefined,而任何后续 .then 都期待返回的 promise 。因此,您需要将代码更改为:

var test = new Promise(function(resolve, reject){
resolve('done1');
});

var test2 = new Promise(function(resolve, reject){
resolve('done2');
});

test
.then(function(data) {
console.log(data);
return test2;
})

.then(resultOfTest2 => doSomething)
.then(function(data) {
console.log(data);
});

关于javascript - JS ES6 promise 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35711084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com