Home > Web Front-end > JS Tutorial > How to Utilize Async/Await with Callbacks in JavaScript?

How to Utilize Async/Await with Callbacks in JavaScript?

Linda Hamilton
Release: 2024-10-30 11:11:05
Original
635 people have browsed it

 How to Utilize Async/Await with Callbacks in JavaScript?

Await Callback Resolution

In a scenario where a simple callback is utilized, such as the example below:

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

converting this function to employ async/await requires a slight alteration. Assuming 'someEvent' is guaranteed to be invoked only once, the 'test' function can be transformed into an async function that awaits the execution of the callback:

async test() {
  return await api.on( 'someEvent' );
}
Copy after login

However, async/await is not inherently capable of handling callbacks directly. To bridge this gap, api.on() must be redesigned to return a Promise. Here's an example:

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

With this modification, the 'test' function can now be written as:

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

Please note that the await keyword is essentially optional in this context, as either approach will still result in a promise being returned.

Finally, it's important to remember that async functions themselves return Promises. As such, accessing the value returned by 'test()' directly is not possible. Instead, the returned Promise needs to be handled:

async function whatever() {
  // snip
  const response = await test();
  // use response here
  // snip
}
Copy after login

The above is the detailed content of How to Utilize Async/Await with Callbacks in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template