遵守承诺不会按顺序返回的JavaScript减少
问题描述:
由于某些原因,所有函数都在同一时间返回。遵守承诺不会按顺序返回的JavaScript减少
我想等待第一个函数解析,然后在调用第二个函数之前调用_done()
,然后调用_done()
,然后调用第三个函数,然后再调用_done()
。
每次调用_done()
我想传递已解析的值从前面的函数调用。
的工作演示是在这里https://repl.it/MeHl/9
"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
答
此代码产生预期的输出
function _test(actions){
return actions.reduce((chain, action) => {
return chain.then(() => action.functionToCall(action.argumentToSend)).then(val => console.log(val));
}, Promise.resolve());
}
function _one(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve('resolvedFromOne');
}, 2000);
})
}
function _two(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve('resolvedFromTwo');
}, 2000);
})
}
function _three(data){
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log(data);
resolve('resolvedFromThree');
}, 2000);
})
}
// not required
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);
'const func = this [action.functionToCall](action.argumentToSend);'已经调用函数。我确信这不是你想到的。 – Tomalak
你的代码如何期待'resolvedFromOne/Two/Three'被记录? –
获得期望的方式就像https://jsfiddle.net/LoL119ep/ –