【发布时间】: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