我正在尝试遍历大量数据并进行异步调用。但是,我的语法不正确
async function getEmailData(conversationId){
fetch(aysynch)
.then(response => {return response.json(); })
.then(data => {
dictionary = {}
console.log(data)
var info = data.Body.ResponseMessages.Items[0].Conversation.ConversationNodes[0].Items[0]
console.log(info)
var conversationId = info.ConversationId.Id
var from = info.From.Mailbox.EmailAddress
var to = info.ToRecipients.map(function(recipient) {return recipient.EmailAddress})
var date = info.DateTimeReceived
dictionary[conversationId] = {'from':from, 'to': to, 'date': date}
return dictionary
})
}
x = [listOfIds] //10 in total
for (i=0; i<x.length; i++) {
console.log(x[i].ConversationId.Id)
let response = await getEmailData(x[i].ConversationId.Id)
let data = await response
console.log(data)
}
这将打印出所有ID,然后在x
中获取列表ID,并运行10次。如何为每个请求提出aysnch请求?
答案 0 :(得分:1)
一些问题:
getEmailData
未返回任何内容。您需要return
承诺链的结果。async
没有用,如果您在此类函数中不使用await
await
函数外部的async
无效。await response
已经是response
的结果,则await
没用let
,var
,const
)这样做:
function getEmailData(conversationId){
return fetch(aysynch)
.then(response => response.json())
.then(data => {
const dictionary = {};
console.log(data);
var info = data.Body.ResponseMessages.Items[0].Conversation.ConversationNodes[0].Items[0];
console.log(info);
var conversationId = info.ConversationId.Id;
var from = info.From.Mailbox.EmailAddress;
var to = info.ToRecipients.map(recipient => recipient.EmailAddress);
var date = info.DateTimeReceived;
dictionary[conversationId] = {from, to, date};
return dictionary;
});
}
(async function() {
let x = [1, 2, 4, 6, 9, 13, 23, 22, 24, 19]; //10 in total
for (let i=0; i<x.length; i++) {
console.log(x[i].ConversationId.Id);
let data = await getEmailData(x[i].ConversationId.Id);
console.log(data);
}
})(); // Immediately invoked
答案 1 :(得分:0)
您应该使用let
。您正在声明全局变量i
。
for (let i = 0; i < x.length; i++) {
console.log(x[i].ConversationId.Id)
let response = await getEmailData(x[i].ConversationId.Id)
let data = await response
console.log(data)
}