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()

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'))


Popular posts from this blog

How to make a Snake Game using JavaScript and html5

How to get user's ip address in JavaScript

Adding Gameover and introduction screen on HTML Canvas

JavaScript intro to classes

How to use canvas context rect method for drawing rectangles