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

213
Visualizações
How do I get the output value of an async method as input and display using express

I am a bit new to node and express

I am trying to build an API that consumes an external API and returns the result as input to what I display

How do I get the output value of an async method as input and display using the express send method

see my express code below

const express = require("express");
var AsyncMethod = require("./src/AsyncMethod");//works perfectly
const app = express();
const port = 8000;

app.get("/url", (req, res) => {
var output = "";
  var biller = new AsyncMethod();
  try {
    output = await (biller.run());
    .then(//need help here
      console.log("inside Main")
    res.send(output))
  } catch (ex) {
    console.log("An error occurred");
    res.send("An error occurred");
    console.log(ex);
  }
});
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

you need to wait for async method execution to completed by using the .then() method and return the response from the callback.

Using Async/Await

const express = require("express");
var AsyncMethod = require("./src/AsyncMethod");//works perfectly
const app = express();
const port = 8000;

app.get("/url", async (req, res) => {
    var output = "";
    var biller = new AsyncMethod();
    try {
        output = await biller.run();
        res.send(output)
    } catch (ex) {
      console.log("An error occurred");
      res.send("An error occurred");
      console.log(ex);
    }

});

Using promise

const express = require("express");
var AsyncMethod = require("./src/AsyncMethod");//works perfectly
const app = express();
const port = 8000;

app.get("/url", (req, res) => {
    var biller = new AsyncMethod();
    biller.run().then(function(output){
      res.send(output)
    }).catch(function(ex){
      console.log("An error occurred");
      res.send("An error occurred");
      console.log(ex);
    })
});
about 4 years ago · Juan Pablo Isaza Relatório

0

I looked at the github project you posted a link to in the comment

.run needs to return a Promise if you want to await it

So - here's how to do that ... the 5 additional lines are marked //+++

var BaseSample = require('./BaseSample');

var GetBillers = function(){
    //inherit
    BaseSample.call(this);
}

GetBillers.prototype.run = function(){
  return new Promise((resolve, reject) => {  //+++
    this.billpayment.get_billers(function(err, res){
        if(err) {
            //error executing request
            console.log("Error calling get billers "+JSON.stringify(err));
            reject(err); //+++
        } else{
            //check if it was successful
            var statusCode = res.statusCode;

            if(statusCode === 200) {//request was successful

                var billerArray = JSON.parse(res.body).billers;
                var firstBiller = billerArray[0];

                var billerId = firstBiller.billerid;
                var billername = firstBiller.billername;
                console.log(billerId+" "+billername);
                resolve(billerId+" "+billername); //+++
            }
            else{//it was not successful for a reason
                console.log("FAILED: "+statusCode);
                reject(statusCode); //+++
            }
        }
    });
  }); //+++
}

module.exports = GetBillers;

Oh, and the code you posted should look a bit like

const express = require("express");
var AsyncMethod = require("./src/AsyncMethod");//works perfectly
const app = express();
const port = 8000;

app.get("/url", (req, res) => {
  var biller = new AsyncMethod();
  try {
    const output = await biller.run();
    console.log("inside Main")
    res.send(output))
  } catch (ex) {
    console.log("An error occurred");
    res.send("An error occurred");
    console.log(ex);
  }
});
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