How to await for a callback to return with JavaScript?

Sometimes, we want to await for a callback to return with JavaScript.

In this article, we’ll look at how to await for a callback to return with JavaScript.

How to await for a callback to return with JavaScript?

To await for a callback to return with JavaScript, we can wrap our callback code in the Promise constructor callback.

For instance, we write

const apiOn = (event) => {
  return new Promise((resolve) => {
    api.on(event, (response) => resolve(response));
  });
};

const test = async () => {
  return await apiOn("someEvent");
};

to create the apiOn function that returns a promise that we create with the Promise constructor.

We call it with a callback that calls resolve with the response to return that as its resolved value.

And then we call apiOn in the test function with the resolved value of the promise returned by apiOn.

Conclusion

To await for a callback to return with JavaScript, we can wrap our callback code in the Promise constructor callback.