How to convert callback function to promise in Javascript

Handle callback, promise and async/await

·

2 min read

Introduce

Introduce i am a new member of Hashnode. Today I will share to newbies to learn javascript as well as async/await in Javascript and how to handle async to apply to your project

For examples

Callback function

Sometimes we will encounter a case where a certain library is written with a callback function.

Callback function is understood as a function, when execution is completed or failed, it will call a function to return that result.

Example callback function:

I have a function listNumbers returns list numbers after 1s and how to get the result

function listNumbers(cb) {
  setTimeout(() => {
    cb([1,2,3]); // response after 1s
  }, 1000);
}

And now I handle the callback function

Let's say I have logic C that will execute when B returns a result and B will wait when A's execution completes. use a callback function like this

a(resA => {
    b(resA, (resB) => {
        c(resB, (resC) => {
            // result
        })
    })
})

As you can see, Logic complex and difficult to maintain code and that's called callback hell :))

Now, I convert callback functions to promise and asynchronous processing with async/await

Before

function listNumbers(cb) {
  setTimeout(() => {
    cb([1,2,3]); // response after 1s
  }, 1000);
}

After

function listMembersAsync() {
    return new Promise((resolve, reject) => {
        listNumbers((res) => {
            if (!res) reject("Error")
            resolve(res)
        })
    })
}

Final

In conclusion, this is a basic tutorial on how to control a callback function and how to pass a callback function to a promise.

Javascript is a great language and I've been working on it for 5 years now. In the near future, I will post more in-depth articles about Backend and software architecture and I am also new to Hashnode, if there is anything wrong, please comment. Thank!!