javascript-today

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.

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

Next Article: async/await