Promise Example

This is an example of a Javascript Promise
mail@pastecode.io avatar
unknown
javascript
3 years ago
603 B
5
Indexable
Never
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
})();