Home >Web Front-end >JS Tutorial >How to Use Async/Await to Pause Execution for Callbacks in JavaScript?

How to Use Async/Await to Pause Execution for Callbacks in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 14:16:02514browse

How to Use Async/Await to Pause Execution for Callbacks in JavaScript?

Using Async/Await to Pause Execution for Callbacks

When dealing with callbacks, it can be desirable to pause a function's execution until the callback has returned a value. In synchronous programming, this can be achieved with blocking mechanisms like join(). However, in asynchronous programming, this is often undesirable.

Suppose you have a callback function that guarantees to be called exactly once, and you want to modify the following function to use async/await:

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

The goal is to convert it to an asynchronous function that awaits the callback execution, like this:

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

Async/await alone cannot achieve this, as it requires a Promise to be returned by api.on(). To remedy this, we can wrap the callback in a Promise-returning function:

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

Now, we can rewrite test() as an asynchronous function:

async function test() {
  return await apiOn( 'someEvent' ); // await is optional here (returns a Promise)
}

Note that async functions also return Promises themselves. To obtain the actual result from test(), it needs to be awaited in an outer async function:

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

By leveraging the Promise-wrapping function, we can use async/await to effectively pause the execution of test() until the callback has returned a value.

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

Statement:
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