我想在节点repl中添加对async/await的支持
发布此问题:https://github.com/nodejs/node/issues/8382
我试过使用这个https://github.com/paulserraino/babel-repl但它缺少async await suppport
我想使用这个片段
const awaitMatcher = /^(?:\s*(?:(?:let|var|const)\s)?\s*([^=]+)=\s*|^\s*)(await\s[\s\S]*)/;
const asyncWrapper = (code, binder) => {
let assign = binder ? `root.${binder} = ` : '';
return `(function(){ async function _wrap() { return ${assign}${code} } return _wrap();})()`;
};
// match & transform
const match = input.match(awaitMatcher);
if(match) {
input = `${asyncWrapper(match[2], match[1])}`;
}
Run Code Online (Sandbox Code Playgroud)
如何将此代码段添加到节点repl上的自定义eval?
节点repl中的示例:
> const user = await User.findOne();
Run Code Online (Sandbox Code Playgroud) 的ECMAScript规范定义了原子能对象在部分24.4.
在所有的全球对象中,这对我来说更加模糊,因为在我没有阅读其规范之前我不知道它的存在,而且谷歌也没有多少引用它(或者名称太过通用和一切都被淹没?).
根据其官方定义
Atomics对象提供在共享内存阵列单元上不可分割地(原子地)操作的函数以及允许代理等待和分派原始事件的函数
因此它具有一个对象的形状,有许多方法来处理低级内存并调节对它的访问.它的公共界面也让我想到了.但是这种对象对最终用户的实际使用是什么?为什么公开?是否有一些可用的例子?
谢谢
实际上我的主要问题是Promise.prototype.catch()在async/await ES8语法中使用,毫无疑问在语法的Promise.prototype.then()本质上存在async/await.
我搜索有关使用Promise.prototype.catch() 中async/await,发现了这个:
async () => {
try {
const result1 = await firstAsynchronousFunction();
const result2 = await secondAsynchronousFunction(result1);
console.log(result2);
} catch(err) {
throw new Error(`Something failed`);
}
}
Run Code Online (Sandbox Code Playgroud)
绝对我知道Promise链接,如:
new Promise((resolve) => {
console.log(`Initial`);
resolve();
})
.then(() => {
console.log(`Task Number One`);
})
.catch(() => {
console.log(`Task in Error`);
})
.finally(() => {
console.log(`All Tasks is Done`);
})
Run Code Online (Sandbox Code Playgroud)
那么,我的问题是如何finally在async/await语法中使用?
我开始使用ES7功能async/await,它提供了处理异步任务的最佳方法,并使您的代码更清晰,更易读.
但是,它不会让您访问由异步函数创建的Promise,因此如果您在异步函数中执行了一些异步请求,则应该对其进行promisify,然后等待它然后返回结果.我是说这个:
async function doStuff() {
//stuff...
var value = await new Promise(function(resolve) {
$.get('http://some/url/...', function(result) {
// stuff...
resolve(result);
});
});
return value;
}
Run Code Online (Sandbox Code Playgroud)
如果你能找到一个指向函数创建的Promise的指针,那么你的代码可能如下所示:
async function doStuff() {
//stuff...
var p = arguments.callee.promise;
$.get('http://some/url/...', function(result) {
// stuff...
p.resolve(result);
});
}
Run Code Online (Sandbox Code Playgroud)
甚至:
async function doStuff() {
//stuff...
$.get('http://some/url/...', function(result) {
// stuff...
async.resolve(result);
});
}
Run Code Online (Sandbox Code Playgroud)
这样您就不需要直接访问Promises API,这使得您的代码完全专注于任务而不需要任何其他功能.
所以我正在使用express.js并考虑使用async/await与节点7.有没有办法我仍然可以捕获错误但摆脱try/catch块?也许是函数包装器?我不确定这将如何实际执行函数的代码并调用next(err).
exports.index = async function(req, res, next) {
try {
let user = await User.findOne().exec();
res.status(200).json(user);
} catch(err) {
next(err);
}
}
Run Code Online (Sandbox Code Playgroud)
像这样......?
function example() {
// Implements try/catch block and then handles error.
}
exports.index = async example(req, res, next) {
let user = await User.findOne().exec();
res.status(200).json(user);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
更类似的东西:
var wrapper = function(f) {
return function() {
try {
f.apply(this, arguments);
} catch(e) {
customErrorHandler(e)
}
}
}
Run Code Online (Sandbox Code Playgroud)
这会以某种方式处理try/catch块但不起作用:
exports.index = wrapper(async example(req, res, next) { …Run Code Online (Sandbox Code Playgroud) 我的函数解析了http服务器启动后立即解析的承诺.这是我的代码:
function start() {
return new Promise((resolve, reject) {
this.server = Http.createServer(app);
this.server.listen(port, () => {
resolve();
});
})
}
Run Code Online (Sandbox Code Playgroud)
如何将启动功能转换为异步/等待?
等待是es7的一个惊人功能.
但是,每当我使用await时,我发现我必须定义一个异步函数并调用此函数.
如
async function asy(){
const [resCityGuess,resCityHot,resCityAll]=await Promise.all([
this.http.get('api/v1/cities?type=guess'),
this.http.get('api/v1/cities?type=hot'),
this.http.get('api/v1/cities?type=group')
])
this.cityGuessName=resCityGuess.data.name;
this.cityGuessId=resCityGuess.data.id;
this.cityHot=resCityHot.data;
this.cityAll=resCityAll.data;
}
asy.apply(this);
Run Code Online (Sandbox Code Playgroud)
我想要的是使用等待没有异步功能,如
// the async function definition is deleted
const [resCityGuess,resCityHot,resCityAll]=await Promise.all([
this.http.get('api/v1/cities?type=guess'),
this.http.get('api/v1/cities?type=hot'),
this.http.get('api/v1/cities?type=group')
])
this.cityGuessName=resCityGuess.data.name;
this.cityGuessId=resCityGuess.data.id;
this.cityHot=resCityHot.data;
this.cityAll=resCityAll.data;
// without call fn
Run Code Online (Sandbox Code Playgroud)
我想定义函数fn并调用此fn有时会重复,所以我想知道是否可以优化这种情况?
我可以使用await而不是异步吗?
非常感谢!
我一直在研究文件中找到的lib属性的可能值是什么意思.我在Typescript GitHub页面上找到了与这些值相对应的相关文件,并且显然使用了以下ES功能:compilerOptionstsconfig.jsond.tsES2017
/// <reference path="lib.es2016.d.ts" />
/// <reference path="lib.es2017.object.d.ts" />
/// <reference path="lib.es2017.sharedmemory.d.ts" />
/// <reference path="lib.es2017.string.d.ts" />
/// <reference path="lib.es2015.d.ts" />
/// <reference path="lib.es2016.array.include.d.ts" />
/// <reference path="lib.es2015.core.d.ts" />
/// <reference path="lib.es2015.collection.d.ts" />
/// <reference path="lib.es2015.generator.d.ts" />
/// <reference path="lib.es2015.iterable.d.ts" />
/// <reference path="lib.es2015.promise.d.ts" />
/// <reference path="lib.es2015.proxy.d.ts" />
/// <reference path="lib.es2015.reflect.d.ts" />
/// <reference path="lib.es2015.symbol.d.ts" />
/// <reference path="lib.es2015.symbol.wellknown.d.ts" />
/// <reference path="lib.es5.d.ts" />
Run Code Online (Sandbox Code Playgroud)
但显然ES6不包括在内,并且它自己的文件没有引用任何内容.我的问题是,如果有人知道,可以安全地假设通过使用es2017 …
typescript ecmascript-6 typescript-typings typescript2.0 ecmascript-2017
我在node 4.3脚本中有一个函数链,类似于回调 - >承诺 - > async/await - > async/await - > async/await
像这样:
const topLevel = (resolve, reject) => {
const foo = doThing(data)
.then(results => {
resolve(results)
})
.catch(err => {
reject(err)
})
}
async function doThing(data) {
const thing = await doAnotherThing(data)
return thing
}
async function doAnotherThing(data) {
const thingDone = await etcFunction(data)
return thingDone
}
Run Code Online (Sandbox Code Playgroud)
(之所以不async/await完全是因为顶级函数是一个任务队列库,表面上不能运行async/await样式)
如果etcFunction()抛出,error泡沫一直上升到顶层Promise吗?
如果没有,我怎么能冒泡errors?我需要每个包装await中try/catch …
我有两个async功能.他们俩都在等待两个3秒的函数调用.但第二个比第一个快.我认为更快的是并行运行和其他串行运行.我的假设是否正确?如果是,为什么会发生这种情况,因为这两个函数看起来在逻辑上相同?
function sleep() {
return new Promise(resolve => {
setTimeout(resolve, 3000);
});
}
async function serial() {
await sleep();
await sleep();
}
async function parallel() {
var a = sleep();
var b = sleep();
await a;
await b;
}
serial().then(() => {
console.log("6 seconds over");
});
parallel().then(() => {
console.log("3 seconds over");
});
Run Code Online (Sandbox Code Playgroud) ecmascript-2017 ×10
javascript ×8
async-await ×6
asynchronous ×3
node.js ×3
ecmascript-6 ×2
express ×1
html ×1
typescript ×1