JS ES6 Promise Chaining [英] JS ES6 Promise Chaining
问题描述
我正在努力学习如何使用承诺,但我无法理解链接。我假设使用此代码,两个承诺都将运行。然后,当我调用test.then()时,它应该知道测试已经解决并将解析数据传递给then()。
I'm trying to learn how to use promises, but am having trouble comprehending the chaining. I assume that with this code, both promises will run. Then when I call test.then() it should know that test has resolved and pass the resolve data to then().
一旦该函数完成,它就会进入next then(),用test2 promise重复相同的过程。
Once that function finishes, it goes onto the next then(), repeating the same process with the test2 promise.
但是,我只能打印出第一个承诺结果,而不是第二个。这里缺少什么想法?
However, I can only get it to print out the first promise results, not the second. Any ideas what is missing here?
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
期待返回的承诺。因此,您需要将代码更改为:
Your first .then
call is returning undefined
, whereas any subsequent .then
is expecting a returned promise. So you'd need to change your code to:
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);
});
这篇关于JS ES6 Promise Chaining的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!