首页 > 解决方案 > 如何使用承诺并稍后在我的代码中使用结果?

问题描述

我是异步操作和 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 在这个阶段是一个承诺,我需要消费它。我该怎么做?我怎样才能得到响应并正确使用它?

标签: javascriptnode.jsasynchronousasync-await

解决方案


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


推荐阅读