【发布时间】:2021-10-12 02:20:28
【问题描述】:
我正在将带有 promise 函数的不同代码 sn-ps 转换为异步等待函数。 VS Code 可以自动完成,但在某些地方我必须手动完成,因为 VS Code 没有突出显示 Promise 语法。谁能给我看一个基于这个表达式将 promise 转换为 async 的例子吗?
const getJson = url => fetch(url).then(res => res.json());
getJson('/i/1.json')
.then(json => {
if (json.key) {
return getJson('/i/2.json')
}
throw new Error('No key')
})
.then(json => {
return json.key2
})
.catch(error => {
console.error(error)
})
关注这篇文章https://advancedweb.hu/how-to-refactor-a-promise-chain-to-async-functions/ 我想我应该得到这样的东西:
const getJson = url => fetch(url).then(res => res.json());
const getJson1 = await getJson();
const getJson2 = await getJson2(key);
const getJson3 = await getJson3(key2);
【问题讨论】:
标签: javascript async-await promise