Promise Example

This is an example of a Javascript Promise
 avatar
unknown
javascript
4 years ago
603 B
8
Indexable
function myPromise(bool = false) {
    return new Promise((resolve, reject) => {
        if (!bool) reject(new Error('Is False'));
        if (bool) resolve('Is True');
    })
}

// Example A

myPromise(true).then((val) => {
    return console.log(val); // Returns "Is True"
}).catch((err) => {
    throw err; // If there is an error or bool is false, the error will be thrown.
})

// Example B

(async () => {
    const res = await myPromise(false);
    const res1 = myPromise(true);

    console.log(res); // Will return promise results
    console.log(await res1) // Will return promise results
})();
Editor is loading...