遍历fetch()调用列表

时间:2019-04-07 19:21:53

标签: javascript

我正在尝试遍历大量数据并进行异步调用。但是,我的语法不正确

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请求?

2 个答案:

答案 0 :(得分:1)

一些问题:

  • 函数getEmailData未返回任何内容。您需要return承诺链的结果。
  • async没有用,如果您在此类函数中不使用await
  • await函数外部的
  • async无效。
  • 如果await response已经是response的结果,则
  • await没用
  • 声明变量(使用letvarconst

这样做:

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