首页 > 解决方案 > 承诺待定

问题描述

为什么这个函数不等待承诺得到回答?如何正确应用 async / await 原则?

我的代码

var axios = require('axios');
var data = JSON.stringify({});


const getClient = async function () {
  
  var config = {
    method: 'get',
    url: `https://reqbin.com/echo/get/json`,
    headers: { 
    },
    data : data
  }

  const res = await axios(config)
  .then(function (response) {
    console.log(response.data)
  })
  .catch(function (error) {
    console.log(error);
  })
  return res
}
console.log(getClient())

终端

Promise { <pending> }
{ success: 'true' }

标签: javascriptpromise

解决方案


为什么这个函数不等待承诺得到回答?

因为你没有等待它。

如何正确应用 async / await 原则?

console.log(await getClient())

注意:需要具有顶级环境await或被移动到async功能中的环境。你可以getClient().then(value => console.log(value))改用。


推荐阅读