Assuming I have a function foo()
which returns a promise
. How would I "start" the async
function foo()
, execute some code while foo()
is resolving, and then go on with the rest of the code after foo()
resolved?
// start async function foo
const somePromise = foo(); // do not use await here in order to execute the following lines
// synchronous code
const a = ....;
const b = ....;
// and then, go on with the rest of the code after the synchronous (const a = ..., const b = ...) and asynchronous (foo()) parts have finished
if(somePromise resolved) { // how to check for resolved promise here
// go on
const bar = a b;
}
CodePudding user response:
Pretty funny you even use the word then
in your question, but:
const somePromise = foo();
// do something synchronous while foo() is resolving
// and then, go on with the rest of the code after the synchronous and asynchronous parts have finished
somePromise.then(() => {
// go on
});
You're better off handling this immediately;
foo().then(() => {
// go on
});
// This happens synchronously
Variant of the first, with await
:
const somePromise = foo();
// do something synchronous while foo() is resolving
// and then, go on with the rest of the code after the synchronous and asynchronous parts have finished
await somePromise;
// go on