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

E2020 dynamic imports in JavaScript

how to dump a postgresql database using from the terminal

JavaScript intro to classes

Tar basic commands to store and extract files

FlappingBird JS13K Games