After reading all the responses here and with my experiences, I would like to resume the detail of callback, promise and async/await
for the asynchronous programming in JavaScript.
1) Callback: The fundamental reason for a callback is to run code in response of an event (see the example below). We use callback in JavaScript every time.
const body = document.getElementsByTagName('body')[0];function callback() { console.log('Hello');}body.addEventListener('click', callback);
But if you must use many nested callbacks in the example below, it will be fairy terrible for the code refactoring.
asyncCallOne(function callback1() { asyncCallTwo(function callback2() { asyncCallThree(function callback3() { ... }) })})
2) Promise: a syntax ES6 - Promise resolves the callback hell issue!
const myFirstPromise = new Promise((resolve, reject) => { // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed. // In this example, we use setTimeout(...) to simulate async code. // In reality, you will probably be using something like XHR request or an HTML5 API. setTimeout(() => { resolve("Success!") // Yay! Everything went well! }, 250)})myFirstPromise .then((res) => { return res.json(); }) .then((data) => { console.log(data); }) .catch((e) => { console.log(e); });
myFirstPromise is a Promise instance that represents the process of async codes. The resolve function signals that the Promise instance has finished. Afterwards, we can call .then() (a chain of .then as you want) and .catch() on the promise instance:
then — Runs a callback you pass to it when the promise has fulfilled.catch — Runs a callback you pass to it when something went wrong.
3) Async/Await: a new syntax ES6 - Await is basically syntactic sugar for Promise!
The Async function provides us with a clean and concise syntax that enables us to write less code to accomplish the same outcome we would get with promises. Async/Await looks similar to synchronous code, and synchronous code is much easier to read and write. To catch errors with Async/Await, we can use the block try...catch
. In here, you don't need to write a chain of .then() of Promise syntax.
const getExchangeRate = async () => { try { const res = await fetch('https://getExchangeRateData'); const data = await res.json(); console.log(data); } catch (err) { console.error(err); }}getExchangeRate();
Conclusion: These are totally the three syntaxes for asynchronousprogramming in JavaScript that you should well understand. So if possible, Irecommend that you should use "promise" or "async/await" forrefactoring your asynchronous codes (mostly for XHR requests) !