JavaScript默认等待而不是手动 [英] JavaScript await by default instead of manually

查看:82
本文介绍了JavaScript默认等待而不是手动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Async / await非常方便,但我想要与他们的行为相反。除非我手动要求他们等待承诺,否则我不希望其他函数继续运行,除非我手动指定它们继续并行运行,否则我希望函数能够产生。

Async/await are really handy, but I want the opposite of their behavior. Instead of other functions continuing on unless I manually ask them to await a promise, I want functions to yield unless I manually specify that they continue running in parallel.

例如,此代码将打印出 1 3 2

For instance, this code would print out 1 3 2:

function wait(ms) {
    return new Promise(r => setTimeout(r, ms));
}

async function a() {
    console.log("1");
    await wait(5000);
    console.log("2");
}

a();
console.log("3");

我希望它打印出来 1 2 3 ,功能 a()直到我等待5秒并打印出2才真正返回。我正在做一个我更喜欢轻量级的扩展,所以我宁愿不使用第三方库。

I want it to print out 1 2 3, with function a() not actually returning until I've waited 5 seconds and 2 has been printed. I'm making an extension that I'd prefer to be lightweight, so I'd rather not use 3rd party libraries.

有没有办法做到这一点?

Is there any way to do this?

推荐答案

隐含等待由于这个博客。简而言之,请考虑为什么不需要锁定JavaScript。这是因为我们不担心被肆无忌惮地抢先一步。

Implicit await is bad, for reasons covered well in this blog. In short, consider why there's no need for locking in JavaScript. It's because we don't worry about being pre-empted willy-nilly.

此外,正如丹尼尔在评论中提到的那样,全球等待,大概是为了向后兼容。

Also, as mentioned by Daniel in comments, global await is not allowed either, presumably for backwards compatibility.

你可以通过包装这样的顶级代码来解决这个问题:

You can work around this by wrapping your top-level code like this:

let wait = ms => new Promise(r => setTimeout(r, ms));

async function a() {
  console.log("1");
  await wait(5000);
  console.log("2");
}

(async () => {

  // Put your top level code here!

  await a();
  console.log("3");

})().catch(e => setTimeout(() => { throw e; }));

不完美,但完成工作,而不是把所有事情颠倒过来。

Not perfect, but gets the job done, without turning everything upside down.

这篇关于JavaScript默认等待而不是手动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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