如何使用express将异步方法的输出值作为输入和显示



我对节点和表达式有点陌生

我正在尝试构建一个API,它消耗外部API并将结果作为输入返回到我显示的

如何使用express send方法获得异步方法的输出值作为输入和显示

见下面我的快递代码

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);
}
});

我看了你在评论

中发布的链接的github项目.run需要返回一个Promise如果你想要await

那么-这是如何做到这一点…附加的5行标记为//+++

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;

哦,你发布的代码应该看起来有点像

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);
}
});

您需要等待使用.then()方法完成异步方法的执行,并返回回调的响应。

UsingAsync/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);
}
});

Usingpromise

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);
})
});

相关内容

  • 没有找到相关文章

最新更新