如何循环请求-承诺API请求调用

How to loop request-promise API request call?

本文关键字:请求 承诺 API 调用 何循环 循环      更新时间:2023-09-26

我正在学习Node.JS,我被介绍到请求-承诺包。我用它来调用API,但我遇到了一个问题,我不能对它应用循环。

这个例子显示了一个简单的API调用:

var read_match_id = {
    uri: 'https://api.steampowered.com/IDOTA2Match_570/GetMatchHistory/V001',
    qs: {
        match_id: "123",
        key: 'XXXXXXXX'
    },
    json: true
};
rp(read_match_id)
.then(function (htmlString) {
    // Process html...
})
.catch(function (err) {
    // Crawling failed...
});

我怎么能有这样的循环:

 var match_details[];
 for (i = 0; i < 5; i++) {
     var read_match_details = {
              uri: 'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001',
            qs: {
                  key: 'XXXXXXXXX',
                  match_id: match_id[i]
                },
            json: true // Automatically parses the JSON string in the response 
    };
    rp(read_match_details)
       .then (function(read_match){
            match_details.push(read_match)//push every result to the array
        }).catch(function(err) {
            console.log('error');
        });
    }

我怎么知道当所有的异步请求完成?

request-promise使用Bluebird作为Promise。

简单解为Promise.all(ps),其中ps为承诺数组。

var ps = [];
for (var i = 0; i < 5; i++) {
    var read_match_details = {
        uri: 'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001',
        qs: {
            key: 'XXXXXXXXX',
            match_id: match_id[i]
        },
        json: true // Automatically parses the JSON string in the response 
    };
    ps.push(rp(read_match_details));
}
Promise.all(ps)
    .then((results) => {
        console.log(results); // Result of all resolve as an array
    }).catch(err => console.log(err));  // First rejected promise

唯一的缺点是,它将在任何promise被拒绝后立即进入catch块。4/5解决了,不要紧,1拒绝了就全扔去接。

另一种方法是使用Bluebird的检查(参考此)。我们将所有承诺映射到它们的反射,我们可以对每个承诺进行if/else分析,并且即使任何承诺被拒绝它也会工作。

// After loop
ps = ps.map((promise) => promise.reflect()); 
Promise.all(ps)
    .each(pInspection => {
        if (pInspection.isFulfilled()) {
            match_details.push(pInspection.value())
        } else {
            console.log(pInspection.reason());
        }
    })
    .then(() => callback(match_details)); // Or however you want to proceed