我正在将带有 Promise 函数的不同代码片段转换为异步等待函数。 VS Code 可以自动执行此操作,但在某些地方我必须手动执行此操作,因为 VS Code 不会突出显示 Promise 语法。有人能给我展示一个基于此表达式将 Promise 转换为异步的示例吗?
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);
最佳答案
类似于
const getJson = async (url) => {
const res = await fetch(url)
return res.json()
}
const yourFetch = async () => {
try {
const json = await getJson('/i/1.json')
if (json.key) {
const json2 = await getJson('/i/2.json')
return json2.key
}
throw new Error('No key')
} catch (err) {
console.error(err)
}
}
关于javascript - 将 Promise 转换为异步等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68612731/