如何在Node.js中使用异步瀑布进行API调用

问题描述

在我的应用程序中,我必须逐步执行一系列API调用。 我尝试使用async Waterfall选项实现此目的,但是在获取一个API的响应之前,第二个函数已被执行,第二个函数也发生了同样的事情。那就是在得到响应之前,最终结果是发送。 如果我尝试执行API调用以外的其他任务,则瀑布操作将正确进行。 以下是我尝试过的代码。为了进行测试,从两个函数(myFirstFunction,mySecondFunction)中调用了相同的API。

const async = require('async');
router.get('/',(req,res) => {
    async.waterfall([
        myFirstFunction,mySecondFunction,],function (err,result) {
            if (err) {
                console.log("Error-->" + JSON.stringify(err));
                res.status(400).json(err).end();
            } else {
                console.log(" Result -->" + JSON.stringify(result));
                res.status(200).json("Success").end();
            }
        });

});

const myFirstFunction = (callback) => {
    console.log(" ------- myFirstFunction ");
    const vehList = callVehicle();
    console.log("First Function -->" + JSON.stringify(vehList));
    callback(null,vehList);
}
const mySecondFunction = (vehList,callback) => {
    console.log("-------- mySecondFunction");
    const vehList1 = callVehicle();
    const vehList2 = {
        "1": vehList,"2": vehList1
    }
    console.log("Second Function -->" + JSON.stringify(vehList2));
    callback(null,vehList2);
}

const callVehicle = () => {
    var options = {
        method: "GET",json: true,strictSSL: false,url: `http://localhost:8080/vehicle/make`
    };
    request(options,function(error,response,body) {
        if (body){
          console.log("Success REST Response: ",JSON.stringify(body));
          return body;
        } else {
          console.log("Error : ",JSON.stringify(error));
          return {"Error": "error"};
        }
      });
}

获得输出

F:\workSpace_Node\SampleApp>node app.js
server running at 9086
 ------- myFirstFunction
First Function -->undefined
-------- mySecondFunction
Second Function -->{}
 Result -->{}
Success REST Response:  {"vehicleList":[{"make":"Audi","model":"A3","vin":"QVFCFQT7894563214"},{"make":"Audi","model":"A4","vin":"ASECFQT7894563214"},"model":"Q7"},"model":"Q5","vin":"QWECFQT7894993214"}]}
Success REST Response:  {"vehicleList":[{"make":"Audi","vin":"QWECFQT7894993214"}]}

如何使用async.waterfall来实现这一目标,或者有什么更好的方法来满足这一要求。

解决方法

对我来说,使用Promises和异步函数的最佳方法。

但是,如果您想在没有承诺的情况下执行此操作,我认为您所有异步的代码都应获取一个回调参数。

但是您的<div className="App-dropdown"> {localStorage.role === "1" && ( <div className="list-dropdown" onClick={() => openTrip()}> <img src={trip} alt="" /> <h5 className="text-dropdown">Trip</h5> </div> )} {localStorage.role === "1" && ( <div className="list-dropdown" onClick={() => openTranscation()}> <img src={buy} alt="" /> <h5 className="text-dropdown">Transaction</h5> </div> )} </div> 没有回调参数,因此callVehicle响应时无法通知父函数。

call Vehicle

有诺言:

const myFirstFunction = (callback) => {
    callVehicle(callback);
}
const mySecondFunction = (vehList,callback) => {
    const vehList1 = callVehicle((err,res) => callback (err,{
    1: vehList,2: res
  }));
}
// We add callback that should be called when we have a result of the api request
const callVehicle = (callback) => {
    var options = {
        method: "GET",json: true,strictSSL: false,url: `http://localhost:8080/vehicle/make`
    };
    request(options,function(error,response,body) {
        if (!error && body){
          console.log("Success REST Response: ",JSON.stringify(body));
          callback(null,body)
        } else {
          console.log("Error : ",JSON.stringify(error));
          callback({ Error: error },null)
      });
}