Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
defining a await for the function in Node.js

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  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.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda