async-await 的行为与.then() 链类似,await 等待承诺得到解决或拒绝,然后继续处理,就像.then() 继续承诺解决和.catch() 承诺拒绝。
await 返回的结果与.then() 获得承诺解决的结果相同,即:
foo().then( function(result){}); // got result here
result = await foo(); // will get same result here too as in above function.
同样,try-catch 中的 catch(err) 与 .then()-.catch() 中的 .catch( function(err) {}) 得到相同的错误。
详细了解async-await here 和here。
要将您的 .then() 转换为 async-await,只需执行以下操作:
(async function () {
try {
const { url } = await server.listen(port);
console.log(`Server ready at ${url}`);
} catch(e) {
// handle errors
}
})(); // This is [IIFE][3]. In this case it's better to have IIFE then regular function, as functions needed to be called.
async-await 作为一个函数:
async function startServer() {
try {
const { url } = await server.listen(port);
console.log(`Server ready at ${url}`);
} catch(e) {
// handle errors
}
}
startServer(); // Not an IIFE