0

I am trying to add query result from in for loop to JSON

function (req,res){
var result  = [{id:1
},{id:2},{id:3}];

for(var i=0;i<result.length;i++){
                        //query run
                       collection.getImages(result[i].id,function (status,error,image) {
                          //add query result to json
                          result[i]['images']=image;

                       });
                   }

 res.json(result);

}

But the final result doesn't contains the newly added key value(ie images) it because collection.getImages() is asynchronous so how can i
solve this?

1 Answer 1

1

You could use Promises to handle your asynchronous calls. Then you can use Promise.all() to await all actions before sending your result back to the client.

var result = [
    {id: 1}, {id: 2}, {id: 3}
];

var promises = [];
for (var i = 0; i < result.length; i++) {
    //query run
    promises.push(new Promise(function (resolve, reject) {
        collection.getImages(result[i].id, function (status, error, image) {
            if (error) {
                reject(error);
            } else {
                resolve(image);
            }
        });
    }));
}

Promise.all(promises).then(function (images) {
    for (var i = 0; i < images.length; i++) {
        result[i]['image'] = images[i];
    }
    res.json(result)
}).catch(function (error) {
    // handle error
});
Sign up to request clarification or add additional context in comments.

1 Comment

I got this error TypeError: Cannot set property 'images' of undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.