由于某种原因,所有功能都在同一时间返回。
我想等待第一个函数解析然后在调用第二个函数之前调用_done()
,然后调用_done()
然后调用第三个函数然后再次调用_done()
。 / p>
每次调用_done()
时,我想传递从前一个函数调用中解析的值。
"use-strict"
function _test(actions){
return actions.reduce((chain, action) => {
const func = this[action.functionToCall](action.argumentToSend);
return chain.then(() => func()).then(val => console.log(val));
}, Promise.resolve().then(val => _done()));
}
function _one(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve();
}, 2000);
})
}
function _two(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve();
}, 2000);
})
}
function _three(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve();
}, 2000);
})
}
function _done(data){
console.log(data);
}
const arrayOfObjects = [
{ functionToCall: '_one', argumentToSend: 'Yay function one was called with this argument' },
{ functionToCall: '_two', argumentToSend: 'Yay function two was called with this argument' },
{ functionToCall: '_three', argumentToSend: 'Yay function three was called with this argument' },
];
_test(arrayOfObjects);
所以日志看起来应该是
Yay function one was called with this argument
resolvedFromOne
Yay function two was called with this argument
resolvedFromTwo
Yay function three was called with this argument
resolvedFromThree
答案 0 :(得分:1)
此代码生成预期输出
function preVisit(v){
nodes[v].preVisit = visitCounter;
visitCounter++;
}
function postVisit(v) {
nodes[v].postVisit = visitCounter;
visitCounter++;
}