How to create promises in JavaScript

Promises enable asynchronous programming, JavaScript is single threaded,
You can use them to wait a lengthy promises take for instance an ajax or fetch process then once ready process the response.

How do declare an asynchronous function,
To declare an asynchronous function add async keyword befor function name;

const func = async function() {
    return 'OK'
}

function func will now return a promise;

const inst = func()
.then(response => console. Log(response))
.catch(err => {
    throw new Error(err)
}

You can also await it like ummm;

const response = await func()
console.log(response)

Rejecting and resolution of promises,
This is done to distinguish successful promises from failed promises

const statusReport = function() {
    return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 10000)
   })
}

You can inquire statusReport as follows;

const analysis = new statusReport()
.then(() => console.log('hooray'), () => console.log('failure'))

Comments

Popular posts from this blog

Introduction to webshare API (navigator.share)

How to use canvas context rect method for drawing rectangles

Redirecting a webpage in JavaScript

How to train a tfjs model on logic gates

JavaScript es6 modules import, export