javascript 在 Web 浏览器或 node.js 中异步/等待?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7704097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:00:52  来源:igfitidea点击:

Async/await in web browser or in node.js?

javascriptasync-await

提问by TN.

Is there any attempt to bring async/awaitfeature from C# 5.0 to any language which can be compiled to JavaScript (such as CoffeScript)? (So it can be used either in web browser or in node.js.)

是否有任何尝试将async/await功能从 C# 5.0 引入任何可以编译为 JavaScript 的语言(例如 CoffeScript)?(所以它可以在 web 浏览器或 node.js 中使用。)

采纳答案by Trevor Burnham

I'm not familiar with C#, but it sounds like what you're looking for is some sort of continuations, so that instead of writing

我不熟悉 C#,但听起来你正在寻找的是某种延续,所以而不是写作

fs.readFile 'foo.txt', (err, data) ->
  myFunc data

you could instead just write something like

你可以写一些类似的东西

data = &fs.readFile 'foo.txt'  # not a real syntax
myFunc data

This isn't something that JavaScript or CoffeeScript provides. However, there are several other compilers that can do something like this:

这不是 JavaScript 或 CoffeeScript 提供的。但是,还有其他几个编译器可以执行以下操作:

  • TameJS- JavaScript-based, mainly just adds this feature
  • Kaffeine- JavaScript-based, adds a bunch of features
  • coco- CoffeeScript-based
  • TameJS- 基于 JavaScript,主要只是增加了这个功能
  • Kaffeine- 基于 JavaScript,添加了一系列功能
  • coco- 基于 CoffeeScript

See also: List of languages that compile to JavaScripton the CoffeeScript wiki.

另请参阅:CoffeeScript wiki 上编译为 JavaScript 的语言列表

回答by user212328

Asyncis on feature list for JavaScript harmony. So far there are numerous attempts to provide such functionality in the browser or in node, none of them seem to be compatible with harmony proposal though:

异步在 JavaScript 和谐的特性列表中。到目前为止,有很多尝试在浏览器或节点中提供此类功能,但似乎没有一个与和谐提议兼容:

  • Async can be simulated with JS1.7 generators (see task.js). Not yet supported out-of-the-box by V8 (without experimental mode), but works in FF. Possibly traceuror Masacracompiler can be used to bring generators to other environments.
  • There is node-fiberslibrary providing other mechanism for asynchronous programming in node (scarifies performance though). Other attempt basing on v8cgi is described here.
  • Rhino has continuationsout of the box providing good alternative. This is why Ringo.jsmight be worth looking at.
  • Few solutions basing on js2js translation are available, e.g: jscx, NarrativeJS, jwacs, StratifiedJS. Some support integration with node.
  • There are many promise/future libraries trying to solve callbacks problem without extending syntax, however they all suffer from composability issues, i.e. cannot use language constructs like loops across callbacks.
  • 可以使用 JS1.7 生成器模拟异步(参见task.js)。V8 尚不支持开箱即用(无实验模式),但可在 FF 中使用。可能可以使用traceurMasacra编译器将生成器带到其他环境。
  • node-fibers库为node 中的异步编程提供其他机制(虽然会降低性能)。此处描述基于 v8cgi 的其他尝试。
  • Rhino 有开箱即用的延续,提供了很好的选择。这就是Ringo.js值得一看的原因。
  • 很少有基于 js2js 翻译的解决方案可用,例如:jscxNarrativeJSjwacsStratifiedJS。一些支持与节点集成。
  • 有许多 promise/future 库试图在不扩展语法的情况下解决回调问题,但是它们都存在可组合性问题,即不能使用诸如跨回调循环之类的语言结构。

回答by Brett Postin

async/await looks to be coming in ECMAScript 7. This proposalwas accepted into stage 1 of the specification process in January 2014.

async/await 看起来会出现在 ECMAScript 7 中。该提案于 2014 年 1 月被接受到规范过程的第一阶段。

The good news is that Googles traceur compileralready supports it, so you could start using it today.

好消息是谷歌的traceur 编译器已经支持它,所以你今天就可以开始使用它了。

Sample syntax:

示例语法:

async function asyncValue(value) {
  await timeout(50);
  return value;
}

async/await is also on the TypeScript roadmap.

async/await 也在TypeScript 路线图上

回答by ajuhos

Yes there is, and you don't even need to compile it, because it is just a simple JavaScript library.

是的,您甚至不需要编译它,因为它只是一个简单的 JavaScript 库。

One of my projects called sharpnr.js has the aim to extend JavaScript with great features of C# (and .NET of course) like await/async, or LINQ.

我的一个名为sharpnr.js 的项目旨在用C#(当然还有.NET)的强大功能来扩展JavaScript,比如await/async 或LINQ。

The library is currently in beta, but it's stable and supports almost every statement (for example loops, switch, if), and works well with existing libraries (like jQuery).

该库目前处于测试阶段,但它很稳定,几乎支持所有语句(例如循环、开关、if),并且可以很好地与现有库(如 jQuery)配合使用。

The await/async syntax is almost identical to the C# version:

await/async 语法几乎与 C# 版本相同:

var getAsync = async(function(url) {
  var result = await; $.get(url);
  $("#test").html(result);
});
getAsync("http://www.sharpnrjs.com");

Working example on jsfiddle.

jsfiddle上的工作示例。

You can download the library from github.

您可以从github下载该库。

回答by Janus Troelsen

When Node 0.11 (with v8 3.19 [1], which has generators[2]) arrives, you can use Galaxyand code like below.

当 Node 0.11(带有 v8 3.19 [1]具有 generators[2])到达时,您可以使用Galaxy和如下代码。

However, only behind a flag. They are supported natively in ioJS.

然而,后面只是一面旗帜。它们在 ioJS得到本地支持

function* countLines(path) {
    var names = yield fs.readdir(path);
    var total = 0;
    for (var i = 0; i < names.length; i++) {
        var fullname = path + '/' + names[i];
        if ((yield fs.stat(fullname)).isDirectory()) {
            total += yield countLines(fullname);
        } else {
            var count = (yield fs.readFile(fullname, 'utf8')).split('\n').length;
            console.log(fullname + ': ' + count);
            total += count;
        }
    }
    return total;
}

function* projectLineCounts() {
    var total = 0;
    total += yield countLines(__dirname + '/../examples');
    total += yield countLines(__dirname + '/../lib');
    total += yield countLines(__dirname + '/../test');
    console.log('TOTAL: ' + total);
    return total;
}

回答by mido

good news,

好消息

nodejs supports it from v7.0.0 (well, partially), still need a harmony flag --harmony_async_await, and apparently has some bugs including memory leak, for more details, but there are some concerns as well, and one commentator advisesto wait till v8 version 55 which might not be long.

nodejs 从 v7.0.0 开始支持它(嗯,部分),仍然需要一个和谐标志--harmony_async_await,显然有一些错误,包括内存泄漏,更多细节,但也有一些担忧,一位评论员建议等到 v8 版本 55这可能不会很长。

回答by niutech

You can have async/await in Google Chrome with Experimental JS flag enabled, using built-in Generators, Promises and a tiny spawn() function by Jake Archibald:

你可以在谷歌浏览器中使用 async/await 并启用实验性 JS 标志,使用内置的生成器、承诺和Jake Archibald 的一个小spawn() 函数

spawn(function*() { //this function is async
      let story = yield getJSON('story.json'); //yield is like await
      addHtmlToPage(story.heading);
});

Alternatively, you can use:

或者,您可以使用:

For browsers not supporting ES6, there is Facebook Regenerator.

对于不支持 ES6 的浏览器,有Facebook Regenerator

回答by TN.

For completeness: I have found that Saltarelle Compiler(which actually compiles C# to JavaScript) also supports await/async.

为了完整性:我发现Saltarelle Compiler(它实际上将 C# 编译为 JavaScript)也支持 await/async。

回答by dmck

If you are interested in .NET style asynchronous programming for JavaScript you should look into Rx for JavaScript. Rx for JavaScrpt is Microsoft's JavaScript port of the Reactive Framework. The reactive framework is described as:

如果您对 JavaScript 的 .NET 风格异步编程感兴趣,您应该查看 Rx for JavaScript。Rx for JavaScrpt 是 Microsoft 的反应式框架的 JavaScript 端口。反应式框架描述为:

A library to compose asynchronous and event-based programs using observable collections and LINQ-style query operators.

一个使用可观察集合和 LINQ 样式查询运算符组合异步和基于事件的程序的库。

You can download Rx for JavaScript here

你可以在这里下载 Rx for JavaScript

And you can read more about it, including examples here

你可以阅读更多关于它的信息,包括这里的例子

You can also install it on node with npm:

您也可以使用 npm 将其安装在节点上:

npm install rx

npm 安装 rx

It works well with libraries like jQuery, however I am not a CoffeeScript programmer, so I'm not sure what support there is for interoperability with other JavaScript libraries in this language.

它适用于像 jQuery 这样的库,但是我不是 CoffeeScript 程序员,所以我不确定有什么支持与这种语言的其他 JavaScript 库的互操作性。

回答by NAVIN

Javascript is providing async-await feature with ECMA 7. Now all asynchronous function can be awaited by promisifying them and waiting for promise to resolve. Most of the asynchronous functions like DB calls, API calls, fs and events are returning promise now in Javascript and nodeJs. Now with async-await code is more cleaner, understandable, debugged.

Javascript 正在为 ECMA 7 提供 async-await 功能。现在所有异步函数都可以通过承诺它们并等待承诺解决来等待。大多数异步函数,如 DB 调用、API 调用、fs 和事件,现在都在 Javascript 和 nodeJs 中返回承诺。现在使用 async-await 代码更清晰、更易于理解、更易于调试。

Example

例子

function timeout(){
  return new Promise( resolve => {
    setTimeout(function(){
      resolve(true);
    }, 5000);
  });
}

async function f(){
    let result = await timeout();
}