Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - JS ES6 Promise Chaining

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().

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);
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...