Welcome to ciysys blog

Javascript setTimeout with async callback

Published on: 6th Sep 2022

Overview

When async version is added to some built-in functions, it can be very confusing whether the function supports an async callback or not.

For example, Array.forEach() does not support async callback while other functions might be supported async callback.

Let test out setTimeout() with async callback and see if it works.

Experiment setTimeout() with an async callback

Let says we have a function that returns a Promise object which looks like this:

function test1(){
    return new Promise(function(resolve, reject) {
        resolve('helo work');
    });
}

And we are going to execute the above function within setTimeout(). Do you think it work?

setTimeout(async () => {
    console.log('timeout..running');
    console.log(await test1());
}, 100);

The result is - yes, it works perfectly.

Conclusion

The ongoing upgrade to the built-in functions make it difficult for the programmer to catch up. But, it is still fun to write program using JavaScript because you learn new stuffs everyday and you will find new way on using async function.

Jump to #JAVASCRIPT blog

Author

Lau Hon Wan, software developer.