首页 > 解决方案 > 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 具有正确的值

谢谢你的帮助

标签: node.jsrequest

解决方案


您没有将内部 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


推荐阅读