Home > front end >  defining a await for the function in Node.js
defining a await for the function in Node.js

Time:08-27

I am trying to get the response data from 3 APIs which is depended on each other. when I call each external API the response has an array of external APIs, as I need all the 3 external APIs responses. Here is the code:

const options = {
    JSON: true,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=UTF-8',
        "Authorization": process.env.authID,
    },
    body: {},
    uri: ''
};

app.post('/sync', async (req, res) => {
    try {
        let getFirstAPI = Object.assign({}, options);
            getFirstAPI.uri = 'https://abcde';   // first API 
        request(getFirstAPI, function (err, httpResponse, body) {
            Promise.all(body.projects.map((prct) => getVuln(prct))).then(rs => {
                res.JSON({ message: rs });
            });
        });
    }
});
async function getVuln(prodId) {
    try {
        let getSecondAPI= Object.assign({}, options);
        getSecondAPI.uri = 'abcd'   prodId.id   '/abc';  //Second API
        return await new Promise((resolve, reject) => {
          request(getSecondAPI, function (err, httpResponse, body) {
                let final = {
                    products: [],
                    dataList: []
                }
                final.products.push({
                    product_id: prodId.id,
                    product_name: prodId.abc,
                    product_ver: prodId.wdc
                })

                body.issues.forEach(csa => {
                  final.dataList.push({
                        product_id: prodId.id,
                        version: csa.Versions,
                        name: csa.Name,
                        pathJsonValue:await getPathfun(csa.link) //Here i am getting error "SyntaxError: Unexpected identifier"
                    });
                });
                resolve(final);
            });
        })

    }
}
 function getPathfun(urlStr) {
    let getPathUrl = Object.assign({}, options);
    getPathUrl.url = urlStr; 
    return new Promise((resolve, reject) => {
        request(getPathUrl, function (err, httpResponse, body) {
            resolve(body);
        });
    });
}

at the "pathJsonValue" I am getting an error while running the code, if I remove the await then "pathJsonValue" is empty. I have attached the error image below. please help me with this issue.enter image description here

CodePudding user response:

  1.       request(getSecondAPI, function (err, httpResponse, body) {
    

Callback must be an ASYNC function to have the possibility to use 'await' keyword inside it.

  1. 'await' keyword doesnt work in "forEach" method. Use for...of loop instead.
  • Related