【问题标题】:Make NodeJS Promise resolution to wait for all processing to finish使 NodeJS Promise 决议等待所有处理完成
【发布时间】:2019-01-18 10:57:30
【问题描述】:

我正在使用 util.promisify 将 Gmail API 调用转换为承诺。

async function listHistory(id, nextId, auth) {
  logger.info("Pulling all changes after historyId: " + id);

  let gmail = google.gmail('v1');

  let list = util.promisify(gmail.users.history.list);

  return list({
    auth: auth,
    userId: 'me',
    startHistoryId: id
  }).then(function(response) {

    if(typeof response !== "undefined") {
        if(typeof response !== "undefined") {
            if(typeof response.data === "object") {
                if(typeof response.data.history === "object") {
                    response.data.history.forEach(function(history) {
                        if(typeof history.messages === "object") {
                          history.messages.forEach(function(message) {
                            getMessage(message.id, auth); // >>> This is a network call
                          });
                        }
                    });
                }         
            }
        }
    }

  }).catch(exception => {
    logger.info("Pulling changes for historyId: " + id + " returned error: " + exception);
  });
}

这是上面调用promise返回函数的代码

let promise = await googleCloudModules.listHistory(currentHistoryId, newHistoryId, oauth2Client).then(response => {
  console.log("DONE!");
}).catch(exception => {
  console.log(exception);
});

承诺甚至在所有处理完成之前就已解决,即 forEach 循环网络调用。只有在 foreach 循环中的所有网络调用都完成后才能解决?

提前致谢。

【问题讨论】:

  • async functions一个(重新)通读。你的异步函数应该返回什么?因为现在它没有返回一个正常的 Promise,你似乎已经通过给它一个 .then.catch 在函数内部传递了 list() 承诺,那么你实际上需要它返回什么?
  • 还要注意你的嵌套if有一些重复,也可以分几个步骤来简化。例如。 if (response && response.data && response.data.history) { let h = response.data.history; h.forEach(...); }

标签: javascript node.js promise


【解决方案1】:

您可以使用 Promise.all 并将所有网络调用映射到一个数组中。以更改一些代码为例

async function listHistory(id, nextId, auth) {
    logger.info("Pulling all changes after historyId: " + id);

    let gmail = google.gmail('v1');

    let list = util.promisify(gmail.users.history.list);

    //you can await the list.
    try {
        const response = await list({
            auth: auth,
            userId: 'me',
            startHistoryId: id
        })
        const getMessagePromiseArray = [];
        if (response && response.data && Array.isArray(response.data.history)) {
            response.data.history.forEach(function (history) {
                if (Array.isArray(history.messages)) {
                    history.messages.forEach(function (message) {
                        getMessagePromiseArray.push(getMessage(message.id, auth)); // >>> This is a network call
                    });
                }
            });
        }
        return Promise.all(getMessagePromiseArray);
    } catch (exception) {
        logger.info("Pulling changes for historyId: " + id + " returned error: " + exception);
    };
}

【讨论】:

    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多