async function f1() {
let r1 = await f2();
console.warn(r1); //4
return r1 + 1;
}
async function f2() {
let r2 = await new Promise((res, rej) => {
setTimeout(() => {
res(1);
}, 1000);
});
let r3;
try {
r3 = await new Promise((res, rej) => {
setTimeout(() => {
rej(2);
}, 1000);
});
} catch (ex) {
console.info(ex); //2
r3 = 3;
}
return r2 + r3;
}
f1().then(v => {
console.log(v); //5
});
注:
(1)任何一个async function声明,实际上都会创建一个async function object,这个object的constructor是AsyncFunction
。
Object.getPrototypeOf(async function(){}).constructor
// function AsyncFunction() { [native code] }
(2)async function调用后返回一个promise,promise resolve的值是async函数最后return
的值。
When an async function is called, it returns a Promise. When the async
function returns a value, the Promise will be resolved with the returned value. When the async function throws an exception or some value, the Promise will be rejected with the thrown value.
(3)await promise表达式会在promise resolve或者reject之后继续执行,如果promise reject了会导致await promise表达式抛异常。
An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.
网友评论