Async - Promsies
Promises are always kept, as they should be. They are guaranteed to return at some time. Many utilites will return a promise now, enabling you to then use that returned promise to watch for when it resolves. I always look for this feature when choosing 3rd party libraries, like axios (for http client)
Promises were introduced with ES6 before that a library like bluebird was needed to take advantage of them. At the time they become officially supported is the same time I feel like JavaScript grew from an adolescent to an adult.
A Promise is always in one of three states guaranteed.
- pending - starts in this state, it has not been fulfilled or rejected yet.
- fulfilled - compleated successfully
- rejected - failed to compleate successfully
To create a new promise
let mypromise = new Promise((resolve, reject) => {
// Do stuff
resolve("somestuff_to_pass_now_that_its_done");
});
more complex to catch errors with the try/catch block
let mypromise2 = new Promise((resolve, reject) => {
try {
// Do stuff
resolve("somestuff_to_pass_now_that_its_done");
}
catch(err) {
reject(`someErr ${err}`);
}
});
Promises can also be chained using the then method.
mypromise.then( (result) => { console.log(result) });
Methods of promise
.then()– does something else with the promise after the previous promise is resolved..catch()– catches errors.finally()– after either a successfull resolve or an error do some stuff.Promise.new()– creates a new promisePromise.all()– takes an array of promises and only executes after all are successful.Promise.allSettled()– takes an array of promises and executes after all are either successful or failed. (Compatible Node.js 12.9.0 & JavaScript ES2020)
Next Article: async/await