Async/await 容许您以一类看上去像并行标识符的形式撰写触发器标识符。 您能采用if句子、for循环式和try/catch在触发器表达式中。
触发器
asyncURL将表达式记号为触发器表达式 。在下面的实例中,test()是两个触发器表达式。
async function test() { return 42;}
const test = async () => 42;
等候
触发器表达式的特定之处是您能采用await关键字。 假如你await依照允诺,awaitURL中止 继续执行周遭的触发器表达式,直至 promise顺利完成或婉拒 esolve反弹。
async function test() { // `await` unwraps the promises value const val = await Promise.resolve(42); val; // 42}test();
在下面的范例中,Promise.resolve() 意味著允诺立刻履行职责。 在下面的实例中,await中止继续执行test()100 微秒:
async function test() { const start = Date.now(); await new Promise(resolve => setTimeout(resolve, 100)); const elapsed = Date.now() – start; elapsed; // about 100}
await 只是两个普通的旧 JavaScript URL。 这意味著您能在内部使用它 if 判断、for 循环式和 try/catch。
async function asyncEvenNumbers() { const nums = []; for (let i = 1; i <= 10; ++i) { if (i % 2 === 0) { const v = await Promise.resolve(i); nums.push(v); } } nums; // [2, 4, 6, 8, 10]}
返回值
触发器表达式的另两个特定属性是它们总是返回两个 Promise,即使您从触发器表达式返回原始值,JavaScript 也会将该值包装在 Promise 中。
async function test() { return 42;}const p = test();p instanceof Promise; // truep.then(v => { v; // 42});
这意味著能采用 await 在触发器表达式调用上:
async function test() { return 42;}async function main() { const val = await test(); val; // 42}
错误处理
采用 async/await 处理错误 是两个复杂的话题。 但是在高层次上,有两种处理错误的模式,当你await在两个 Promise 上,而那个 Promise 拒绝了,await抛出两个错误,你能try/catch捕捉:
async function test() { try { await Promise.reject(new Error(Oops)); } catch (err) { err.message; // Oops }}
async function test() { const promise = Promise.reject(new Error(Oops)); // Unwrap the promises error const err = await promise.catch(err => err); err.message; // Oops}