我有以下方法流
编辑:最后一个方法返回一个promise,我希望它传播回链中的第一个方法。 (我知道如何直接从承诺返回到调用函数,不知道它将如何传播到链中?)
function A (input) {
//do something, input = ...
B (input)
.then( (result) => { console.log(result) })
.catch ( (error) => { console.log(error) });
}
function B (intermediate1) {
//do something, intermediate1 = ....
return new Promise ( (resolve, reject) => {
C(intermedediate1)
.then( (result1) => {
//do something to result1
resolve(result1);
})
.catch( (error1) => {
reject(error1);
})
}
}
function C (intermediate2) {
//do something, intermediate2 = ....
return new Promise ( (resolve, reject) => {
D(intermedediate2)
.then( (result) => {
//do something to result
resolve(result);
})
.catch( (error) => {
reject(error);
})
}
}
function D (request) {
return new Promise ( (resolved, reject) => {
//some ASYNC task with request with result and error returned
if (error)
return reject(error);
resolve(result);
}
}
函数A执行输入操作,调用B,执行更多操作,调用C等等,直到D调用异步方法并返回promise。
我不知道如何将这个承诺传播回C,B,最后是A?当我从D中回复承诺时,我想在每个方法中做一些事情,依此类推。
答案 0 :(得分:-1)
我认为你正在寻找类似的东西。
function A (input) {
//do something, input = ...
B (input).then(function(){console.log("resolved")});//here B() will return a promise object
}
function B (intermediate1) {
//do something, intermediate1 = ....
return C(intermediate1);
}
function C (intermediate2) {
//do something, intermediate2 = ....
return D(intermediate2);
}
function D (request) {
return new Promise ( (resolve, reject) => {
//some ASYNC task with request with result and error returned
setTimeout(function(){resolve()});
if (false)
return reject(error);
//resolve(result);
})
}
A()