通过错误处理处理for循环中的多个promise

时间:2017-03-08 10:49:28

标签: node.js promise

我想处理多个承诺,例如下面kouta API返回多个站点然后我想在网站上循环以逐个获取类别。

节点代码:

request({
        url: 'https://cbatest.kounta.com/v1/companies/20155/sites.json',
        headers: header_data,
        json: requestData,
        method: 'GET',
    }, function (err, response, body) {
        var site_list = body;
        //res.send(site_list);
        var promises = [];
        for (let i = 0; i < site_list.length; i++) {
            var cat_list = new Promise(function (resolve, reject) {
                var site_id = site_list[i].id;
                var category_arr = [];
                request({
                    url: 'https://cbatest.kounta.com/v1/companies/20155/sites/' + site_id + '/categories.json',
                    headers: header_data,
                    json: requestData,
                    method: 'GET',
                }, function (err, response, body) {
                    var category_list = body;
                    resolve(category_list);
                });
            });
            cat_list.then(function (result) {
                promises.push(result);
                console.log(promises);
                res.send(promises)
            }).catch(function (err) {
                console.log(err);
            })
        }
    });

问题:console.log(promises);只适用于最后一个id和res.send(promises);只工作一次。我错过了什么?

提前致谢。

2 个答案:

答案 0 :(得分:1)

您的代码仅针对已解决的第一个承诺发送结果。

最好从async

使用

代码变得像:

request({
        url: 'https://cbatest.kounta.com/v1/companies/20155/sites.json',
        headers: header_data,
        json: requestData,
        method: 'GET',
    }, function (err, response, body) {
        var site_list = body;
        //res.send(site_list);
        var promises = [];

    async.map(site_list, function(site, callback){
                request({
                    url: 'https://cbatest.kounta.com/v1/companies/20155/sites/' + site.id + '/categories.json',
                    headers: header_data,
                    json: requestData,
                    method: 'GET',
                }, function (err, response, body) {
                    var category_list = body;
                    callback(null, category_list);
                });

    }, function(err, result){
        if(err) return res.send(err);

        //result is array of arrays. you can shape it like you want
        res.send(result);
    });

    });

答案 1 :(得分:0)

这是简单的解决方案

const companiesPromise = fetch('https://cbatest.kounta.com/v1/companies/20155/sites');
const categoriesPromise = fetch('https://cbatest.kounta.com/v1/companies/20155/sites/categories');

Promise
    .all([companiesPromise,categoriesPromise])
    .then(responses => {
        return Promise.all(responses.map(res => res.json()))
    })
    .then(responses => {
      console.log(responses)
    })
    .catch(err => {
      console.error(error)
    })