javascript - 承诺待定
问题描述
为什么这个函数不等待承诺得到回答?如何正确应用 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' }
解决方案
为什么这个函数不等待承诺得到回答?
因为你没有等待它。
如何正确应用 async / await 原则?
console.log(await getClient())
注意:需要具有顶级环境await
或被移动到async
功能中的环境。你可以getClient().then(value => console.log(value))
改用。
推荐阅读
- amazon-web-services - Dynamodb 查询:使用过滤器表达式获取匹配的对象
- mysql - 无法查询 ApplicationDbContext,方法需要 1 个参数
- javascript - 为什么 req.session.token 中的字符串不等于 req.headers 中的字符串?
- redis - REDIS 中的 SCAN / HSCAN 命令是否有任何推荐的 COUNT 值?
- r - 将元素附加到列表数组中的列表
- html - SVG:半透明线条的混合取决于笔画宽度?
- postgresql - 将值转换为文本并返回其原始类型是否总是在 Postgres 中有效?
- javascript - 处理多个按钮的按钮动画
- javascript - 如何使用 AJAX 调用为不同的选项卡加载表数据
- visual-studio - 使用 VS2019 上未显示的产品密钥解锁