如何“等待"回调返回? [英] How to "await" for a callback to return?

查看:273
本文介绍了如何“等待"回调返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用简单的回调(例如下面的示例)时:

When using a simple callback such as in the example below:

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

如何更改功能以使用异步/等待?具体来说,假设"someEvent"被保证只能被调用一次,那么我希望函数测试是一个异步函数,该异步函数在执行回调之前不会返回,例如:

How can the function be changed to use async / await? Specifically, assuming 'someEvent' is guaranteed to be called once and only once, I'd like the function test to be an async function which does not return until the callback is executed such as:

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

推荐答案

async/await不是魔术.异步函数是可以为您解开Promises的函数,因此您需要api.on()才能返回Promise才能正常工作.像这样:

async/await is not magic. An async function is a function that can unwrap Promises for you, so you'll need api.on() to return a Promise for that to work. Something like this:

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

然后

async function test() {
  return await apiOn( 'someEvent' ); // await is actually optional here
                                      // you'd return a Promise either way.
}


但这也是一个谎言,因为异步函数也会返回Promises本身,所以您实际上不会从test()中获取值,而是对值的承诺,您可以这样使用:


But that's a lie too, because async functions also return Promises themselves, so you aren't going to actually get the value out of test(), but rather, a Promise for a value, which you can use like so:

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

这篇关于如何“等待"回调返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆