I am trying to run to promises (which make some rest API calls on each). Based on the result of the two promises, use the third function to process the data. Also, the functions running in sequence can be changing. So I made them in a dynamic way of constructing promise.
However, the promises seem to be starting without the previous one ending. Here is a simplified model for testing the same concept.
var funcs = [
() => {
console.log('Task 1 Sart =', new Date());
sleeper(6000, 'Task 1 Resolved');
console.log('Task 1 Return');
},
() => {
console.log('Task 2 Sart=', new Date());
sleeper(5000, 'Task 2 Resolved');
console.log('Task 2 Return');
},
() => {
console.log('Task 3 Start=', new Date());
console.log('Task 2 Return');
}
];
function sleeper(m, msg) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(console.log(msg, new Date()));
}, m);
});
}
function runSequence(functionSequence) {
return functionSequence.reduce((p, func) => {
return p.then(func);
}, Promise.resolve());
}
var v = runSequence(funcs);
The results look like this VM128:51 Task 1 Sart = Wed Jun 07 2017 13:54:34 GMT-0700 (PDT) VM128:53 Task 1 Return VM128:56 Task 2 Sart= Wed Jun 07 2017 13:54:34 GMT-0700 (PDT) VM128:58 Task 2 Return VM128:61 Task 3 Start= Wed Jun 07 2017 13:54:34 GMT-0700 (PDT) VM128:62 Task 2 Return VM238:69 Task 2 Resolved Wed Jun 07 2017 13:54:39 GMT-0700 (PDT) VM238:69 Task 1 Resolved Wed Jun 07 2017 13:54:40 GMT-0700 (PDT)
I would assume I don't see the second task start till the first one ended. Looked like they all started in sequence. Is anything I missed or totally misunderstand how the promises work. What I tried to achieve is to have the first one completed and then the following starts
Promise
or other value is returned from functions infuns
array, i.e.g,return sleeper(6000, 'Task 1 Resolved');
– Briannareturn
thePromise
from the function, else there is no way to determine that the task has been completed at the anonymous function call which performs an asynchronous procedure. You are close, thoughsleeper()
call, where you have returned aPromise
, is not returned from anonymous function call. See also #44381082? – Brianna.then()
callback (which is what's needed here), and even if it did that wouldn't be sufficient to make this a dupe. – Autocatalysisreturn
, and possibly a chained.then()
is necessary, if the secondconsole.log()
call is expected to be called afterPromise
returned fromsleeper()
call is resolved, as demonstrated at linked jsfiddle. – BriannaPromise
value is inconsequential to the issue at current Question. The gist of issue at Question is the thePromise
object is notreturn
ed from the anonymous function calls withinfuncs
array, as described at each link a duplicate Questions "return
" is mentioned at each link – Brianna