Aus irgendeinem Grund kehren alle Funktionen zur gleichen Zeit zurück.JavaScript reduzieren mit Promises, die nicht sequenziell zurückkehren
Ich möchte warten, bis die erste Funktion auflöst, dann _done()
anrufen, bevor ich die zweite Funktion anrufe, und dann _done()
anrufen, dann die dritte Funktion anrufen und dann _done()
erneut aufrufen.
Jedes Mal, wenn _done()
aufgerufen wird, möchte ich die Werte übergeben, die aus dem vorherigen Funktionsaufruf gelöst wurden.
Die Arbeits Demo ist hier 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);
So das Protokoll wie
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
'const func = dies [action.functionToCall] (action.argumentToSend);' ruft bereits die Funktion auf. Ich bin sicher, das war nicht das, was Sie vorhatten. – Tomalak
Wie erwartet Ihr Code, dass 'resolvedFromOne/Two/Three' protokolliert wird? –
Der Weg zu bekommen, was Sie erwarten, ist wie https://jsfiddle.net/LoL119ep/ –