"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Handle Asynchronous Callbacks Using Await?

How to Handle Asynchronous Callbacks Using Await?

Published on 2024-11-11
Browse:993

How to Handle Asynchronous Callbacks Using Await?

Asynchronous Callback Handling with Await

In certain scenarios, while using callbacks like:

test() {
  api.on( 'someEvent', function( response ) {
    return response;
  });
}

you may need to incorporate asynchronicity. To make this function asynchronous and use await, you must first ensure that the callback function (someEvent) returns a Promise. This is because async functions rely on Promises to complete asynchronous operations.

A revised version of api.on():

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

Using this updated function, you can now modify test() to be an asynchronous function:

async function test() {
  return await apiOn( 'someEvent' );
}

However, asynchronous functions also return Promises, so the actual result value of test() is a Promise that can be resolved within another asynchronous function:

async function whatever() {
  // snip
  const response = await test();
  // use response here
  // snip
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3