我试图更好地理解async functionJavaScript在技术上是什么,即使我基本上知道如何使用它们.
对async/await的许多介绍都相信async函数基本上只是一个承诺,但事实上并非如此(至少不是Babel6-transiled代码):
async function asyncFunc() {
// nop
}
var fooPromise = new Promise(r => setTimeout(r, 1));
console.clear();
console.log("typeof asyncFunc is", typeof asyncFunc); // function
console.log("typeof asyncFunc.next is", typeof asyncFunc.next); // undefined
console.log("typeof asyncFunc.then is", typeof asyncFunc.then); // undefined
console.log("typeof fooPromise is", typeof fooPromise); // object
console.log("typeof fooPromise.next is", typeof fooPromise.next); // undefined
console.log("typeof fooPromise.then is", typeof fooPromise.then); // function
Run Code Online (Sandbox Code Playgroud)
尽管如此,它绝对有可能成为await一种承诺await fooPromise().
它是一个async funtion属于自己的东西,await …
给定一个函数,fn它返回一个promise,以及一个任意长度的数据数组(例如data = ['apple', 'orange', 'banana', ...])如何按顺序将数组的每个元素上的函数调用链接起来,这样如果fn(data[i])解析,整个链完成并停止调用fn,但是如果fn(data[i])拒绝,下一个呼叫fn(data[i + 1])执行?
这是一个代码示例:
// this could be any function which takes input and returns a promise
// one example might be fetch()
const fn = datum =>
new Promise((resolve, reject) => {
console.log(`trying ${datum}`);
if (Math.random() < 0.25) {
resolve(datum);
} else {
reject();
}
});
const foundResult = result => {
// result here should be the first value that resolved …Run Code Online (Sandbox Code Playgroud) 我在写我的第一Koa.js的应用程序,并且最近已经被引入到ES2016(又名ES7)功能的过程async/ await,我想利用这些.
我发现我的谷歌技能不能胜任这项任务,我能找到的代码片段很少是标准的Koa(使用发生器),或者不像ES7那样边缘化.
请参阅下面的答案,了解我如何运行测试.
我有一个es2017代码与async/await,我想将它转换为es5,以便大多数Node.js版本都支持它.
我当前的.babelrc文件如下所示:
{
"presets": ["es2015", "es2016", "es2017"]
}
Run Code Online (Sandbox Code Playgroud)
所以我将es2017改为es2016,从es2016到es2015,从es2015到es5.
当我在构建它之后尝试运行代码时,babel src -d dist -s我收到错误说:ReferenceError: regeneratorRuntime is not defined
如何将es2017代码转换为es5?我想稍后发布代码并使其可以通过node.js v4及更高版本使用.