Reputation: 1396
I have a few javascript functions that return promises. I'm using .then
to act on the data returned from those functions. However, is the order guaranteed in the below code? Will result2
get processed after result
?
const test = promiseReturningFunction(data);
test.then((result) => {
doStuff(result);
});
const test2 = promiseReturningFunction2(data2);
test2.then((result2) => {
doStuff(result2);
});
Or should this be rewritten along the lines of:
const test = promiseReturningFunction(data);
test.then((result) => {
doStuff(result);
}).then(() => {
const test2 = promiseReturningFunction2(data2);
test2.then((result2) => {
doStuff(result2);
});
});
In short: is .then
blocking?
Upvotes: 0
Views: 41
Reputation: 92639
No, .then()
is not blocking. In the first code snippet, you don't know if result
will be processed first or result2
.
You could try the async functions syntax, it's easier to understand:
(async () => {
const result = await promiseReturningFunction(data);
doStuff(result);
const result2 = await promiseReturningFunction2(data2);
doStuff(result2);
})();
await
means that the execution of this code will be stopped until the promise returned by promiseReturningFunction
is resolved.
Upvotes: 2
Reputation: 665316
No, the order of then
callbacks on independent promises is not guaranteed. This is pretty much necessary to allow concurrent processing of multiple asynchronous tasks.
If you need a particular order, you need to explicit chain your promise callbacks.
In your case, if you just need the two doStuff
calls to run after each other, but want to concurrently process the two promiseReturningFunction
s, you can use
const p1 = promiseReturningFunction(data);
const p2 = test.then(doStuff);
const p3 = promiseReturningFunction2(data2);
Promise.all([p2, p3]).then((stuff, result2) => doStuff(result2));
If you want to have the two promiseReturningFunction
s run sequentially, then your second snippet is fine.
Upvotes: 2
Reputation: 680
First one is asynchronous there is no guaranty for result1 after result2
promiseReturningFunction(data);
.then((result) => {
doStuff(result);
})
.then(()=>promiseReturningFunction2(data2))
.then((result2) => {
doStuff(result2);
})
.catch((err)=> /* Error handling **/);
Try this structure please
make sure doStaff is not any I/O operation or else you have make them promise returnable function
Upvotes: 0