How to convert Callback to Promise in JavaScript/Node.js?

Tram Ho

I’m TUAN, currently a Full-stack Developer in Tokyo.
If you find this Blog interesting, please give me a like and subscribe to support me.

Callback : In JavaScript,  callback is a function passed as a parameter to another function. The function executes as soon as the result of the calling function is ready. Simply put, it handles JavaScript asynchronous requests.

Example best to demonstrate this is to use a function setTimeout() take a function callback and delay execution exam code. As soon as the function timeout expires, the callback function will execute.

Output:

Hello! GeeksforGeeks

Promise: It is very similar to the callback commands in action. However, the advantage of using Promises is to improve readability of code as it saves us from callback hell.
Promise has four states:

  • Pending: The promise is still incomplete. Neither success nor failure.
  • Fulfilled: Promise ended successfully.
  • Reject: Promise ends with an error.
  • Settled: Promise has failed or failed.

Convert an existing callback to a Promise:

Output:

Steps to convert above code into Promise:

    • Create a function named error and insert the error handling code block above the callback function in it.
    • Create a function called success and insert the block code on success above in it.
    • Then modify the caller code by returning a promise.

object

  • Use the functions success and error in any of the following ways.
  • See below code for better understanding.

Output:

Let’s apply them to Nodejs.

Install Nodejs and set up a simple Node application by following the steps shown here .

Example: Here, the scenario is we have a array student with id and name</strong > are the value . We need to get name of student having given id. We are given an existing callback directive that needs to be converted to a promise.

Output:

We can now convert the callback function into promise functions. Here we can repeat the previous steps, i.e. Error logic in function failure and Success logic in function < strong>success. See the code below for more information.

Output:

As always, I hope you enjoyed this post and learned something new.

Thank you and see you in the next posts!

If you like my blog, click follow to support me. Thank you.

Ref

Share the news now

Source : Viblo