How to make a function wait until a callback has been called using Node.js?

Sometimes, we want to make a function wait until a callback has been called using Node.js.

In this article, we’ll look at how to make a function wait until a callback has been called using Node.js.

How to make a function wait until a callback has been called using Node.js?

To make a function wait until a callback has been called using Node.js, we can run our code in the callback that’s called when the operation is done.

For instance, we write

const f = (query, callback) => {
  myApi.exec('SomeCommand', (response) => {
    callback(response);
  });
}

to define the function f that takes the callback parameter.

We call that in the callback that’s called when myApi.exec is done.

We call callback with response as the argument to pass response to the callback.

Then we can call f to get the response value with

f(query, (returnValue) => {
  // ...
});

We get response from the returnValue.

Conclusion

To make a function wait until a callback has been called using Node.js, we can run our code in the callback that’s called when the operation is done.