先看下面链接代码
这里是promise解决回调地狱的方法
将上述的promise代码改进
async function readFileData() {
//像同步写法:但是是一个异步的结果
try {
// await 使用必须伴随着async函数的包裹
const aData = await getFileContent('a.json')
console.log('a data', aData)
const bData = await getFileContent(aData.next)
console.log('b data', bData)
const cData = await getFileContent(bData.next)
console.log('c data', cData)
} catch (err) {
console.error(err)
}
}
readFileData()
注意
1. await 后面可以追加 promise 对象,获取 resolve 的值
2. await 必须包裹在 async 函数里面
3. async 函数执行返回的也是一个 promise 对象
4. try-catch 截获 promise 中 reject 的值