0

I have following request to api:

api.get_info(name, function(err, data) {
    if (err) {
        return console.log(err);
    }
    result.push(data);
});

On this request I got in response only for one product, but have 10 products for which should receive result from api and send in response to client side.

I tried add api call on loop:

app.get('/info', (req, res) => {
    let products = ["product 1", "product 2", ... "product 10"];

    let full_info = [];

    for (let product of products) {
        api.get_info(product, function(err, data) {
            if (err) {
                return console.log(err);
            }
            full_info.push(data);
        });
    }

    res.json(full_info);
});

Now sent response before got all info. How to send response when will get all data?

Does it possible implement without async and promises ?

Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46

1 Answers1

0

You may find async.js interesting for this.

In your case:

async.each(products, function (product, callback) {
    api.getInfo(product, callback);
}, function (err, datas) {
    res.json(datas);
}
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94