JavaScript Promise API

Promises can replace the asynchronous use of callbacks, and they provide several benefits over them.

Basic Promise Usage

A new Promise is created with the new Promise() constructor and the promise provides resolve and reject functions to the provided callback. The fulfillment of the promise is simply logged, via a fulfill callback set using then() method.

A Promise is in one of these states

pending: initial state, not fulfilled or rejected.
fulfilled: it means the asynchronous operation has completed, and the promise has a value.
rejected: meaning that the operation failed, and the promise will never be fulfilled. In this state, a promise has a reason that indicates why the operation failed.

Promise methods

Promise.all()
Promise.prototype.catch()
Promise.prototype.then()
Promise.race()
Promise.reject()
Promise.resolve()

Promise.all()

Sometimes we may have to execute multiple async interactions but only want to response when all of them are completed, yeah that’s where Promise.all() method comes in. The Promise.all() method takes an array of promises and fires one callback once they are all resolved.

Lets change officeWorkCompleted = true to officeWorkCompleted = false than the promise will return rejected failed message.

Promise.all is rejected if one of the elements is rejected and Promise.all fails fast. If you have four promises which resolve after a timeout, and one rejects immediately, then Promise.all rejects immediately.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.