JavaScript Promises

Description

Resource list

I have gotten some knowledge from this article below:

More on Promises

Quick Note

  • JavaScript is a synchronous programming language, but callback functions can make it work like an asynchronous programming language.
  • Promises can be resolved or rejected.
  • Promise can return one of these status; pending, fulfilled, rejected.
//Promises are created this way;
new Promise(function(resolve, reject) {
    //code block
})
//the executing function accepts two parameters, resolve and reject which are callback   functions.

//Promises are used for handling asynchronous operations also called blocking code. Once that completes, it either calls resolve on success or reject on error.
let promise = new Promise(function(resolve, reject) {
    if(promise_kept) {
        resolve("done");
    } else {
        reject(new Error("error occured"));
    }
}

Consuming Promises

const finished = new Promise()
const checkIfFinished = () => {
    finished
        .then(ok => {
            console.log(ok)
        }) 
        .catch(err => {
            console.error(error)    
        })
}
checkIfFinished(); //This will execute the finished() promise and wait for it to resolve, using the then callback. If there is an error, it will be handled in the catch block.

There's more to promises which will be detailed as it is used on projects.