Ahmet Meliksah Akdeniz
meliksahakdeniz

meliksahakdeniz

Promise()

Promise()

Ahmet Meliksah Akdeniz's photo
Ahmet Meliksah Akdeniz
·Feb 1, 2022·

4 min read

This was something too confusing for me in the past, I do not know why. Since I will start learning NodeJS soon, I need to make sure I cover this.

A promise is > The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. -MDN

Now, what the heck does that even mean??? Basically, it keeps a code chunk ready according to what may or may not happen in the future and sets your code ready for both scenarios. This might be useful especially when receiving data. I made my own dummy data though, I did not get data from an API.

The promise() takes two parameters; resolve and reject. JS runs resolve when, well, the promise is kept (in this case when you receive data). Otherwise, JS runs reject.

Here, take a look

const promise= new Promise((resolve, reject) => {
  resolve("Data received");
  reject("ERROR");
});

I have assigned a promise to promise variable - I am so creative lol. Do not worry about the reject() by the way because once JS runs into resolve() it will not even look at reject(). 0.PNG

In a scenario where we do not receive the data, the reject method will do its job, and the terminal will run this, let me show you the code first: (commented out resolve method)

const promise= new Promise((resolve, reject) => {
  // resolve("Data received"); 
  reject("ERROR");
});

1.PNG

Now, what is all that?! I know the error message is too long, but understanding the fact that we did not catch our error is enough. Simply put, JS tells us that telling that there is an error is not enough, you need to catch the error using .catch() Let me add some more code

const promise= new Promise((resolve, reject) => {
  // resolve("Data received"); 
  reject("ERROR");
});

promise
  .then((value) => {
    console.log(value);
  })
  .catch((err) => {
    console.log(err);
  });

I used the then() method to catch our resolve method and the catch() method to catch our reject method. Once we add this block of code, we will get rid of the error on the terminal. Look at the terminal now

2.PNG

Here is a real-world example. As you may know, there are thousands of blogs added every day, so I kind of mimicked that and wrote a program that lists, adds, and receives blog data.

const blogs = [
  { title: "title 1", author: "author 1" },
  { title: "title 2", author: "author 2" },
  { title: "title 3", author: "author 3" },
];

const blogList = (blogArray) => {
  blogArray.map((blog) => {
    console.log(blog);
  });
};

const addBlog = (blog, array) => {
  return new Promise((resolve, reject) => {
    array.push(blog);
    resolve(array);
    reject("Could not add blog information, please try again later!");
  });
};
addBlog({ title: "title 4", author: "author 4" }, blogs)
  .then((value) => {
    console.log(value);
  })
  .catch((err) => console.log(err));

Here is the code breakdown:

This is my dummy data, a simple array of objects.

const blogs = [
  { title: "title 1", author: "author 1" },
  { title: "title 2", author: "author 2" },
  { title: "title 3", author: "author 3" },
];

This is the function that lists the blogs. map() creates a new array with the results of called function within it. But, here I did not ask it to do anything special, I just asked it to log each element on the terminalç

const blogList = (blogArray) => {
  blogArray.map((blog) => {
    console.log(blog);
  });
};

And this is the final part of my code that adds a blog to target array

const addBlog = (blog, array) => {
  return new Promise((resolve, reject) => {
    array.push(blog);
    resolve(array);
    reject("Could not add blog information, please try again later!");
  });
};


addBlog({ title: "title 4", author: "author 4" }, blogs)
  .then((value) => {
    console.log(value);
  })
  .catch((err) => console.log(err));

In short, we push the blog(in this case our blog argument is { title: "title 4", author: "author 4" }) argument into array (in this case our array argument is blogs) argument.

When we successfully receive the data, we just resolve our promise, which means we display our array, otherwise, we will simply give a warning with our reject method.

In the last chunk of code, we call our addBlog() function and pass in our arguments (blog, array) separated by commas. Finally, we catch our resolve and reject function using then and catch methods

 
Share this