【问题标题】:How to consume a promise and use the result later on with my code?如何使用承诺并稍后在我的代码中使用结果?
【发布时间】:2021-08-16 00:55:23
【问题描述】:

我是异步操作和 js 的新手。这是我的问题。 我有一个 Person 类。我想使用从 API 调用中获得的数据来初始化 Person 实例。

class Person { 
    constructor(data) {
        this.data = data;
    }
}

我正在使用 Axios 进行 API 调用。我收到回复并想在课堂上使用它。

const res = axios.get('https://findperson.com/api/david');
const david = new Person(res);

我明白 res 在这个阶段是一个承诺,我需要使用它。 我该怎么做? 我怎样才能接受响应并正确使用它?

【问题讨论】:

  • 您已经用async/await 标记了您的问题,所以看来您知道正确的方法。你能告诉我们你试过的cde吗?

标签: javascript node.js asynchronous async-await


【解决方案1】:

axios.get() 返回一个对象的承诺,其中包含返回的数据、状态、标题等...

async function getPerson() {
  try {
    const res = await axios.get('https://findperson.com/api/david');
    const david = new Person(res.data);
    // do something with david
  } catch (error) {
    console.log(error)
  }
}

function getPerson() {
  axios
    .get('https://findperson.com/api/david')
    .then(res => {
      const david = new Person(res.data)
      // do something with david
    })
    .catch(console.log)
}

【讨论】:

    【解决方案2】:

    在另一个 async 函数中,或者在模块的顶层或 REPL 中(在节点 16.6+ 或更早版本中启用了 --experimental-repl-await 功能),您可以只使用 await

    const res = await axios.get('https://findperson.com/api/david');
    

    这将等待 promise 被解析并解包以将包含的值存储在 res 中。

    如果您想从异步世界中获取价值并进入同步领域,您必须通过回调函数对其进行处理:

    axios.get('https://findperson.com/api/david').then(
      res => { 
          // do stuff with res here
      });
    

    ...但不要上当;如果没有await,那么在axios.get 调用之后的任何代码都将立即运行,而无需等待回调。因此,您不能在回调中执行诸如将 res 复制到全局 var 之类的操作,然后期望在后续代码中对其进行设置;它必须一直回调。

    【讨论】:

    • 您必须将 await 包装在异步函数中,否则会出现错误。
    【解决方案3】:

    你可以这样做:

    axios.get('https://findperson.com/api/david').then(res => {
            const david = new Person(res);
        });
    

    或者在 async 函数中:(参见 async await for javascript)

    const res = await axios.get('https://findperson.com/api/david');
    const david = new Person(res);
    

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 2019-06-09
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 2014-12-15
      • 2023-03-22
      相关资源
      最近更新 更多