Ell*_*iot 8 javascript chaining promise es6-promise
我正在努力学习如何使用promises,但我很难理解链接.我假设使用此代码,两个承诺都将运行.然后,当我调用test.then()时,它应该知道测试已经解决并将解析数据传递给then().
一旦该函数完成,它将进入下一个then(),用test2 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);
});
Run Code Online (Sandbox Code Playgroud)
Geo*_*lah 17
你的第一个.then电话正在返回undefined,而后续的任何一个电话都.then在期待返回的承诺.因此,您需要将代码更改为:
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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10523 次 |
| 最近记录: |