javascript - 将 Promise 转换为异步等待

标签 javascript async-await promise

我正在将带有 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/

相关文章:

c# - 使用 Async 避免重复代码

node.js - 在 Nodejs 中使用 async await 与 redis 和 bluebird

javascript - 如何在 Python 中编写一系列 Promise?

javascript - bootstrapDialog 失败,querySelector is not a function

javascript - 在带有 ui-view 的 angularjs 中使用 jssor slider 时出现错误

javascript - 获取 Div 中 '-' 之后直到第一个字符的所有文本

javascript - ReactJS : Should on express. js 或其他一些中间件来处理 React 应用程序中的登录和 session ?

javascript - 如何在执行下一行代码之前完成等待订阅 block ?

javascript - 如何使用 async/await 在 NodeJS 中创建 TCP 客户端?

javascript - 从 Facebook Messenger 中检索 first_name 会导致 [object Promise]