我的意思是下面的代码只是同步运行:
someReceiveACallback('event', async () {
const result = await imAsync() /*1*/
let anotherResult = null /*2*/
if (result.authenticated)
anotherResult = await imAlsoAsync() /*3*/
send(anotherResult) /*4*/
})
流只是:1-> 2-> 3-> 4,就像是同步的。
如果默认行为是异步的,那么当它确实使事物同步时,为什么将其标记为async
?
答案 0 :(得分:2)
async
和await
是Promise
的“语法糖”。这意味着该语法等效于ES2015和ES2016中的以下语法,将generator function作为coroutine运行(在示例中纠正语法错误之后)
someReceiveACallback('event', function() {
return coroutine(function*() {
const result = yield imAsync(); /*1*/
let anotherResult = null; /*2*/
if (result.authenticated)
anotherResult = yield imAlsoAsync(); /*3*/
send(anotherResult); /*4*/
}).apply(this, arguments);
});
function coroutine(fn) {
return function() {
return new Promise((resolve, reject) => {
const gen = fn.apply(this, arguments);
const step = method => result => {
try { var { value, done } = gen[method](result); }
catch (error) { reject(error); return; }
if (done) { resolve(value); }
else { Promise.resolve(value).then(_next, _throw); }
};
const _next = step('next');
const _throw = step('throw');
_next(undefined);
});
};
}
Original code generated by babel
简单来说,只有第一个遇到的await
表达式之前的所有内容都是同步运行的。这是由于_next(undefined)
构造函数的执行程序中的Promise
调用。
此后,函数将一个诺言返回给调用方,该诺言在函数的执行已达到其控制流的结尾时进行结算。
连续遇到的await
表达式之间的每个块都在其自己的异步延续.then(...)
中运行。
协程的目的是在生成器中遇到的每个promise resolution procedure表达式上运行yield
。当承诺达成时,协程会在同一点异步地重新进入控制流,提供已解决的值或抛出被拒绝的原因。 Promise.resolve(value).then(_next, _throw)
是做什么的
有了对async
/ await
的本地支持,coroutine()
完成的所有操作实际上都在运行时的事件循环中实现。
答案 1 :(得分:-1)
此代码无法同步运行。它只是按顺序运行,看上去是同步的。 如果您的函数使用异步方法,则可以将其标记为“异步”类型。
然后'await',标记异步部分