node.js - Await .then 不等待结束才返回
问题描述
async / await / .then 在继续之前不会等待函数结束。
async function getInfosDatastore(req, res, next) {
var IP = req.body.IP;
var username = req.body.username;
var password = req.body.password;
var token = '';
var cluster = "";
var policies = "";
var datastores = "";
url = 'https://simplivity@' + IP + '/api';
await getInfos.getToken(url, username, password)
.then(response => {
token = response;
getInfos.getDatastores(token, url)
.then(response => {
datastores = response;
});
getInfos.getPolicies(token, url)
.then(response => {
policies = response;
});
getInfos.getClusters(token, url)
.then(response => {
cluster = response;
});
});
res.json({ name: datastores, policy: policies, cluster: cluster });
}
输出是:-令牌-测试-res.json(但它是空的)-每个函数中的console.log
它应该是: - 令牌 - 每个函数中的 console.log - 测试 - res.json 具有正确的值
谢谢你的帮助
解决方案
您没有将内部 Promise 与外部 Promise 链链接在一起。改成
async function getInfosDatastore(req, res, next) {
const { IP, username, password } = req.body;
const url = 'https://simplivity@' + IP + '/api';
const token = await getInfos.getToken(url, username, password);
const [name, policy, cluster] = await Promise.all([
getInfos.getDatastores(token, url),
getInfos.getPolicies(token, url),
getInfos.getClusters(token, url)
]);
res.json({ name, policy, cluster });
}
使用await Promise.all
,在解释器继续下一条语句之前,等待所有内部 Promise(并提取它们的解析值)。
此外,如果您还没有,请确保在其中一个 Promise 拒绝的情况下将 acatch
放在调用者上。getInfosDatastore
推荐阅读
- reactjs - 如何获取文档 ID 和文档数据?
- mysql - 获取一个没有通话记录的随机客户,并按他们未接听的电话数量排序
- spring - Spring WebClient Post 方法正文
- visual-c++ - 在 MSVC 2017 上使用 _addcarry_u64 时结果错误
- php - 当我在 laravel 查询上运行代码时,我变得乱码
- database - 如何在 tsql 的循环中转到下一列
- autodesk-forge - 如何在 3D 视图中查看 dwg - 客户问题
- c# - Vuforia 编辑默认脚本
- spring-boot - Spring Boot 1.5.8 与 Jakson 2.10.0 对象映射问题
- ms-access - MS Access 表单查询日期范围(甚至没有)