Random posts about ... stuff
by Q
JavaScript provides three different ways to implement an asynchronous function: callback, promise, async/await. They achieve the same goal: let the program continue while you are still waiting for an event occur.
This post will only focus on the syntax difference of using callback, promise and async/await. Making the code simple, we want to let our program print out some strings after certain period of time. For example, let the program print “Hello World!” after sleeping for 1 second.
If we code in Python, we can have something as following:
Same goal can be achieved by using callback in JavaScript:
Using promise or async/await can be little more complicated in this situation. setTimeout() takes a function as input and it doesn’t return a Promise object. Therefore, we will need to convert setTimeout into a Promise object to align with promise or async/await’s syntax.
Reference: