0

I am trying to make an API call for each loop from the first API that provides an array of responses. In the end results, all the responses from the second API need to be pushed to an array.

const request = require('request');
const options = {
    JSON: true,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=UTF-8',
        "Authorization": process.env.authID,
    },
    body: {},
    uri:''
};
 app.post('/vuln/sync', (req, res) => {
    try {
        let getProject = Object.assign({}, options);
        getProject.uri = 'first API';
        getProject.body = {

        }
        request(getProject, function (err, httpResponse, body) {
            if (err) {
                return console.error(err);
            }
            let finalData = [];
            body.projects.forEach(function (prct) {
            let valu = getVuln(prct);
            finalData.push(valu)
            })
          res.send({ message: finalData });  /// now this data is empty
           

        });

    } catch (err) {
        console.error(err);
        return res.status(500).send(err);
    }

});
function getVuln(res) {
    try {
        let getSecondAPi = Object.assign({}, options);
        getSecondAPi.body = {
        }
        getSecondAPi.uri = 'second API'+res.id+'/XYZ';
        request(getSecondAPi, function (err, httpResponse, body) {
            if (err) {
                return console.error(err);
            }
            console.log(body); //
            return body;
        });
    } catch (err) {
        if (error.status !== 409) {
            console.log(error);
        }
    }
}

The current code gives me the empty "{message : [null, null]}", can you please help me with this?

isherwood
  • 58,414
  • 16
  • 114
  • 157
santosh
  • 192
  • 9

1 Answers1

1

There are 2 issues:

  1. you use sync forEach to call async functions.
  2. getVuln function should return promise but now it return undefined

I would write like that:

async function getVuln(res) {
    try {
        let getSecondAPi = Object.assign({}, options);
        getSecondAPi.body = {
        }
        getSecondAPi.uri = 'second API'+res.id+'/XYZ';
        return await new Promise((resolve,reject)=>{
         request(getSecondAPi, function (err, httpResponse, body) {
            if (err) {
               console.error(err);
               reject(error)
            }
            console.log(body);
            resolve(body);
         });
        })
        
    } catch (err) {
        if (error.status !== 409) {
            console.log(error);
        }
    }
}

then e.g make a parallel requests:

const finalData = await Promise.all(body.projects.map((prct)=>getVuln(prct)))
//or
Promise.all(body.projects.map((prct)=>getVuln(prct))).then(res=>{finalData=res})
Andrey Smolko
  • 712
  • 3
  • 8