【问题标题】:Convert Promise to Async Await将 Promise 转换为异步等待
【发布时间】: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


    【解决方案1】:

    类似

    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)
      }
    }
    

    【讨论】:

      【解决方案2】:

      await(除了模块)仅在 异步函数 内有效。所以让我们创建一个异步 IIFE

      const url = "https://jsonplaceholder.typicode.com";
      const getJson = async url => await fetch(url).then(res => res.json());
      
      ;(async () => { // Async IIFE
          
        const getJson1 = await getJson(`${url}/users/1`);
        if (!getJson1.id) throw new Error('No ID');
        const getJson2 = await getJson(`${url}/todos/${getJson1.id}`);
        console.log(getJson2);
      
      })();
      
      console.log("PS: I don't wait for the above to finish");

      如果您事先知道路径,您可以选择Promise.all

      const getJson = (url) => fetch(url).then(res => res.json());
      
      Promise.all([
        getJson("https://jsonplaceholder.typicode.com/users/1"),
        getJson("https://jsonplaceholder.typicode.com/todos/1")
      ]).then((res) => {
        console.log("Both are done!")
        console.log(res[0]);
        console.log(res[1]);
      });

      【讨论】:

      • 顶级等待是一回事,但有一些注意事项
      • @Evert 除非在模块中使用:v8.dev/features/top-level-await - 目前 AFAIK 没有顶级等待之类的东西。顶级等待总是会抛出一个错误。
      • 你的回复自相矛盾,但我想你明白了。
      • @Evert 比我们彼此了解。 OP 没有提供也没有提到对 JS 模块的任何使用。
      猜你喜欢
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2020-03-04
      • 2018-08-03
      • 2021-05-17
      • 2015-12-13
      相关资源
      最近更新 更多