实现说明
await 点把异步工作排成序列,拒绝落在取结果的那一行。
各个操作都建立在顶层绑定之上:ok、failed、recovered。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 文件的状态由几个模块级绑定持有:ok、failed、recovered。
核心语句
.then((message) => `recovered from ${message}`);
const ok = await Promise.resolve('{"qty":2}')
.then((text) => JSON.parse(text))
.then((data) => data.qty * 100)
.then((cents) => `charge ${cents} cents`);
.catch((error) => `failed: ${error.name}`);
代码示例
// 链上任何一步抛错:后续 then 全部跳过,rejection 沿链传到最近的 catch
const ok = await Promise.resolve('{"qty":2}')
.then((text) => JSON.parse(text))
.then((data) => data.qty * 100)
.then((cents) => `charge ${cents} cents`);
console.log(ok);
// JSON.parse 抛出的 SyntaxError 被链尾的 catch 接住,中间步骤不再执行
const failed = await Promise.resolve('not-json')
.then((text) => JSON.parse(text))
.then((data) => data.qty * 100)
.then((cents) => `charge ${cents} cents`)
.catch((error) => `failed: ${error.name}`);
console.log(failed);
// catch 返回普通值即恢复 fulfilled,链可以继续走下去
const recovered = await Promise.reject(new Error('boom'))
.catch((error) => error.message.toUpperCase())
.then((message) => `recovered from ${message}`);
console.log(recovered);