簡體   English   中英

使NodeJS Promise解析以等待所有處理完成

[英]Make NodeJS Promise resolution to wait for all processing to finish

我正在使用util.promisify將Gmail API調用轉換為Promise。

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);
  });
}

這是上面的承諾返回函數調用的代碼

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

甚至在所有處理完成之前,即forEach循環網絡調用之前,也會兌現承諾。 我只能在foreach循環中的所有網絡調用完成后才能解析它嗎?

提前致謝。

您可以使用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);
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM