Promises in JavaScript

Promises in JavaScript

Promises seem to be one part of Asynchronous JavaScript beginners tend to skip, however it is at the core of "Asynchronousity" people prefer to use the usual async and await without understanding what goes on behind the scene.

For the purpose of beginners i will like to define certain terms that will be used in the Article:

Asynchronous:

Simply means occurring at the same time i.e one operation can be ongoing while another is in operation too.

Callbacks:

A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.

This article is targeted towards beginners and intermediates who still don't understand what Promises are and how they can be used.

Callback Hell:

Callback hell is a phenomenon that afflicts a JavaScript developer when he tries to execute multiple asynchronous operations one after the other. By nesting callbacks in such a way, we easily end up with error-prone, hard to read, and hard to maintain code.

Why do we really use promises

Promises are used to handle asynchronous operations in JavaScript (Callback hell). Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events. Promises are "Continuation events" and they help you execute the multiple async operations together in a much cleaner code style.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The code will stop executing until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point.

Thanks to the Promises API , developers are able to avoid a lot of callbacks (just taking a callback or passing a callback doesn't mean it's asynchronous) to handle async interactions, which now can be handled as any other variable.

What is a Promise

A promise is an object that may produce a single value some time in the future : either a resolved value, or a reason that it's not resolved (e.g., a network error occurred).

It is a class native in JavaScript that takes in a callback function in JavaScript if the callback function is fulfilled it dishes our resolve else it rejects the promise.

So let's say we promise have a promise named event, if the name is "Chibueze" the name promise will be fulfilled else the promise will be rejected.

We initialize a promise using the new key word and it accepts 2 arguments which are functions namely resolve and reject

const event =new Promise((resolve, reject)=>{
let name="Chibueze"
if(name==="Chibueze"){
  resolve("Correct! Promise Passed")
}
else{
reject("Promise Failed")}
})

So we basically create a promise and check if the name we initialized is same with the name in the each object, If it is same we dispatch a resolve with an argument of "Correct Promise Passed" else a resolve that dispatches a reject of "Promise Failed".

All promises instances will have a then method which allows you to do something when the promise is fulfilled. The then method callback receives the result given to it by the resolve execution.

Ekran-Resmi-2020-06-06-12.21.27.png

Promises are usually used when we want processes to occur asynchronously, that is running one activity does not stop because of one is running, most computation really take time and can slow down our app from processing other information or functions necessary and this basically where we use promises.

So how do we now access the value of our promise using the async-await keyword or using the .then in JavaScript.

So let us access our event promise

event.then(res=>console.log(res)).catch(err=>console.log(err))

promises.png

.then is for the resolve it takes in the value of the resolve parameter and logs it to do console, while the .catch takes in the value of the reject parameter and logs it assuming the promise is not fulfilled.

The above code with result to a "Correct! Promise Passed"

Async await

1_m-1v5d5Uo92sN6s0zxAriQ.png

This is more modern to Javascript than the .then() syntax, especially when making API requests. So we design a function called getNameResult()

const getNameResult=async()=>{
 const data=await event;
 console.log(data)
}
getNameResult()

When we run the above code it gives us same result as the .then syntax and it's also asynchronous, we basically await our promise computation to be done then console.log(data) that is return when we run the function.

Promise.resolve & Promise.reject

Untitled-1.jpg

The Promise.resolve() method returns a Promise object that is resolved with a given value. If the value is a promise, that promise is returned; if the value is a then-able (i.e. has a "then" method), the returned promise will "follow" that then-able, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

let promise = Promise.resolve("Chibueze");

promise.then((val)=> {
    console.log(val); //Chibueze
});

Promise.reject() The Promise. reject() method returns a Promise object that is rejected with a given reason.

var promise = Promise.reject("Assume error of Null");

  // Catch the promise and pass the
  // function for logging the error in console
  promise.catch((error) =>{
    console.log(error);
  });

Fulfilling Multiple Promises at the same time -Promise.all()

The promise API allows us to compute multiple APIs at the same time, Promise.all takes an array of promises and creates a promise that fulfills when all of them successfully complete. You get an array of results (whatever the promises fulfilled to) in the same order as the promises you passed in.

let promiseOne = new Promise(function(resolve,reject){
    resolve("First Promise Solved");
});

let promiseTwo = new Promise(function(resolve,reject){
    resolve("Second Promise Solved");
});

var checkFulfill = [promiseOne,oromiseTwo];

Promise.all(checkFulfill).then((arrOfPromiseResults)=>{
    console.info(arrOfPromiseResults);
});

// Outputs ["First Promise Solved","Second Promise Solved"]

You see it's that simple. Happy Coding.


However if you are new to nodeJS try decoding what this does in the comment section, thank you.

const getText = (path) => {
  return new Promise((resolve, reject) => {
    readFile(path, "utf8", (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};


getText("./content/first.txt")
  .then((result) => console.log(result))
   .catch((err) => console.log(err));

When we run the above function what are we expecting? Drop your feedback in the comment section, thank you.