首页 > 解决方案 > 如何获得基于异步等待/承诺的响应

问题描述

所以我有一个代码如下。有一个函数调用 2 个 axios 请求来获取一些示例 API 数据。

function fetch_records(){
  var api_url1 = "https://api.github.com/users/mojombo"
  var api_url2 = "https://api.github.com/users/defunkt"

  axios.get(api_url1)
    .then(function (response) {
      console.log('Data1 received: ',response);
    })
    .catch(function (error) {
      console.log(error);
    })

  axios.get(api_url2)
    .then(function (response) {
      console.log('Data2 received: ',response);
    })
    .catch(function (error) {
      console.log(error);
    })
}

然后我想运行这个函数 fetch_records() 如下

console.log('Script started');
fetch_records();
console.log('Script ended');

所以输出应该是

Script started
... api response data ...
Script ended

但是因为 Javascript 是异步的,所以它总是给出如下输出

Script started
Script ended
... api response data ...

我相信 async/await 或 promise 用于实现我想要的响应,但我不确定如何准确使用它。

标签: javascriptasync-awaitaxios

解决方案


只需使用async/await关键字,但请记住 JS 始终是 JS。

async function fetch_records() { // a async function
  var api_url1 = "https://api.github.com/users/mojombo"
  var api_url2 = "https://api.github.com/users/defunkt"

  // waterfall way
  const data1 = await axios.get(api_url1); // await
  console.log('Data1 received: ', data1);

  const data2 = await axios.get(api_url2); // await
  console.log('Data2 received: ', data2);

  // parallel way
  // const [data1, data2] = await Promise.all([
  //   axios.get(api_url1),
  //   axios.get(api_url2)
  // ]);
  // console.log(data1, data2);
}

(async () => {
  try {
    console.log('Script started');
    await fetch_records(); // await a async function (Thenable object)
    console.log('Script ended');
  } catch(err) {
    console.error(err);
  }
})();

推荐阅读