Asynchronous Programming in JavaScript: Promises
javascript·@ghasemkiani·
0.000 HBDAsynchronous Programming in JavaScript: Promises
JavaScript is a single-threaded programming system. However, a lot of tasks are performed asynchronously by the host environment. Async tasks do not follow the ordinary flow of the program, because it is not determined when they will be resolved or if they will encounter an error. For doing an async task, you need to use a callback function in the very least. However, if you are going to do several async tasks in tandem, your nested callbacks will soon make the program unreadable or unmaintainble. This is where promises come in. A promise is an object with a `then` method that is called when an async task has been resolved or rejected. In order to create a promise, you can use the `Promise` constructor. For example: ``` let promise = new Promise((resolve, reject) => { try { let result = asyncTask(); resolve(result); } catch(e) { reject(e); } }) ``` The promise has a `then` method that accepts two parameters: ``` .then(onResolve, onReject) ``` If the promise is resolved, the `onResolve` handler is called with the result. If there was an error, the `onReject` handler is called with the reason of rejection. There is also a `catch` method that handles only the rejection cases: ``` .catch(onReject) ``` On the other hand, the promise has also a `finally` method with a handler that is called after the promise has been either resolved or rejected: ``` .finally(handler) ``` Promises are especially useful for chaining several async tasks: ``` Promise.resolve(a) .then(a => asyncTaskA(a)) .then(b => asyncTaskB(b)) .then(c => asyncTaskC(c)) .catch(e => console.log(e)) .finally(() => cleanUp()); ``` The promises make an elegant solution for dealing with async tasks. However, there is a newer method for this purpose, namely the `async` and `await` keywords, that I will discuss in the next post.
👍 ghasemkiani, nanocheeze, charisma1, rimon24, econchain, smileplease, aponanda56, sam1210, rkaitra, dxdei, thepreacher, danielvd, pdng1975, johnwjr7, cryptoeagle, manuel78, calimeatwagon, fikrihaikal, satyamsharma, nataliemk, pepskaram, shahbazfayyaz, steem-bot, lunaticmoon, stendekq, hafiz34, zpzn, muhammadreza, haji, cheema1, rohit12123, raihan12123, skolin, marijan, egorinbar, ademas, harbecity, adasq, akmalf, nayim533,