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

JavaScript introduction to variables

Solutions to blocked URLs on Facebook

How to set content disposition headers for express nodejs apps

How to stop moz dotbot from accessing your website

How to set content disposition header for nginx server to force content download