Run Code Only After Asynchronous Function Finishes Executing

Run a second function only after the first function is completely finished

Make async the functions that are awaitable (return a Promise)

// DEMO ONLY Just a helper to wait some ms time and return a Promise
const wait = (t) => new Promise((r) => setTimeout(r, t));

const firstFunc = async () => {
await wait(1000); // Just to fake some wait time
console.log("first one");
}

const secondFunc = () => { // This does not need to be async
console.log("second one");
}

const run2functions = async() => {
await firstFunc(); // Await for this one
secondFunc(); // You don't need to await for this one
};

run2functions();

Why does an async function finishes executing after a promise started later?

You're surprised why async1 end comes after promise2 and promise3, although it was called before them, and microtasks are executed in the order they are enqueued.

However, it really boils down to how many microtasks does it take for the async function to resolve.

Take a look at this (it's the same code but with 4 raw promises):

async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}

async function async2() {
console.log('async2 start');
return new Promise((resolve, reject) => {
resolve();
console.log('async2 promise');
})
}

console.log('script start');

setTimeout(function() {
console.log('setTimeout');
}, 0);

async1();

new Promise(function(resolve) {
console.log('promise1');
resolve();
}).then(function() {
console.log('promise2');
}).then(function() {
console.log('promise3');
}).then(function() {
console.log('promise4');
});

console.log('script end');
/* Just to make the console fill the available space */
.as-console-wrapper {
max-height: 100% !important;
}

Run code only after asynchronous function finishes executing

Well, you simply call the function at the end of the asynchronous callback. That is when the asynchronous callback has ended - it is when everything else in the asynchronous callback has finished! So, for example:

func myMethod() {
// ... code ...
somebody.doSomethingWith(someObject, asynchronousCallback: {
(thing, otherThing) in
// ... do whatever
// --> CALL THE FUNCTION!
})
// ... code ...
}

If the problem is that you do not know what function to call, you can configure your surrounding function / object so that someone can hand you a function which is then what you call in the spot where I said "call the function" in the above.

For example:

func myMethod(f:() -> ()) { // we receive the function as parameter
// ... code ...
somebody.doSomethingWith(someObject, asynchronousCallback: {
(thing, otherThing) in
// ... do whatever
// --> CALL THE FUNCTION, by saying:
f()
})
// ... code ...
}


Related Topics



Leave a reply



Submit