简体   繁体   English

异步/等待方法问题

[英]Async/Await Method Issue

I am working on MERN Stack Application(Mean,Express,ReactJS,NodeJS).我正在研究 MERN 堆栈应用程序(平均值、Express、ReactJS、NodeJS)。 I have one issue is that I have many more methods in mlcontroller.js page and I call some methods on REST API so I call that methods under that API from mlrouter.js but all that API is Async so currently API takes data slots vise means I give u an example that in one time take 100 data from first method and then pass to another method and pass from all methods again come to first method and take next 100 data and repeat same process again but I need to take all data in one time means untill one method will not complete not move on another method how's that possible with node js? I have one issue is that I have many more methods in mlcontroller.js page and I call some methods on REST API so I call that methods under that API from mlrouter.js but all that API is Async so currently API takes data slots vise means我给你一个例子,一次从第一个方法中获取 100 个数据,然后传递给另一个方法,然后再次从所有方法传递到第一个方法,获取下一个 100 个数据并再次重复相同的过程,但我需要将所有数据放在一个时间意味着直到一种方法无法完成才继续使用另一种方法节点js怎么可能?

I place my code here:我把我的代码放在这里:

mlrouter.js mlrouter.js

  ensureApiAuthenticated,
  authController.checkReadOnlyUser,
  mlController.getAPIData,
  mlController.getData,
  mlController.getCRCDetails,
  mlController.getDetails,
  mlController.uploadData
  )

MlController.js MlController.js

async function getAPIData(req, res, next) {
  try {

    let loanboardapi = " ", dealersocket = " ";
    loanboardapi = {
      url: "https://loanboard.houstondirectauto.com/api/User/GetAuthorizationToken?username=amin@houstondirectauto.com&password=test@123",
      method: "GET"
    };
    dealersocket = {
      url: 'https://idms.dealersocket.com/api/authenticate/GetUserAuthorizationToken?username=ankur@houstondirectauto.com&password=H5d465@!ddfdd45dsfd688&InstitutionID=105815',
      method: 'GET'
    };
    request(loanboardapi,
      (err, res, body) => {
       console.log("res = ", res);
        console.log("body =", body);
        loantoken = JSON.parse(body).token;
        console.log(loantoken);

      });
    request(dealersocket,
      (err, res, body) => {
        console.log("res = ", res);
        console.log("body =", body);
        dealertoken = JSON.parse(body).Token;
        console.log(dealertoken);
         next();
      });

  }
  catch (e) {
    req.error = e;
    next();
  }
}
 function getData(req, res, next) {
  try {

    let result;

    request.get('https://idms.dealersocket.com/api/account/getaccountlist?token=' + dealertoken + '&LayoutID=2002313&PageNumber=1&accounttype=i&accountstatus=a,c,b,o,r,s,x',
      (err, res, body) => {
        console.log("res = ", res);
        console.log("body =", body);
        result = JSON.parse(body);
        console.log(result);
        totalpage = parseInt(result.TotalPages);
        let resultdata = Object.assign({}, result.Data);
        console.log(resultdata);
        //getSSN(totalpage, dealertoken, next);
         next();
        
      })
  }
  catch (e) {
    req.error = e;
    next();
  }
}
async function getCRCDetails(req,res,next) {
  async.eachSeries(ssn, async (item) => {
    let CBCOptions = {
      method: "POST",
      url: "https://loanboard.houstondirectauto.com/api/Report",
      headers: {
        "Content-Type": "application/json",
        Cookie: "ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p",
      },
      body: JSON.stringify({
        token: loantoken,
        action: "CBCReport",
        variables: {
          ssn: item,
        },
      }),
    };
    let EMpInfoption = {
      method: "POST",
      url: "https://loanboard.houstondirectauto.com/api/Report",
      headers: {
        "Content-Type": "application/json",
        Cookie: "ci_session=udmojmlc5tfl3epbrmtvgu6nao2f031p",
      },
      body: JSON.stringify({
        token: loantoken,
        action: "getEmployerInfo",
        variables: {
          ssn: item,
        },
      }),
    };
    try {
      let resultCBCOptions = await requestpromise(CBCOptions);
      let EmployerInfoOptions = await requestpromise(EMpInfoption);
      console.log(resultCBCOptions)
      console.log(EmployerInfoOptions)
      CRCOptions.push(resultCBCOptions);
      EmpOption.push(EmployerInfoOptions);
      
    } catch (error) {
      console.log(error);
    }
  },
  () => {
  
     next();
  }
);

}
async function getDetails(req,res,next) {
  for(let i =0;i<CRCOptions.length;i++){
      for(let j=0;j<EmpOption.length;j++){
        let resdata = JSON.parse(CRCOptions[i]);
        console.log(resdata);
        result = resdata.data.DigifiResponse;
        console.log(result);
        
        let bodydata = JSON.parse(EmpOption[i]).data;
        
       let crcssn = JSON.parse(CRCOptions[i]).ssn;
       let empssn = JSON.parse(EmpOption[i]).ssn;
       console.log("CRCSSN=",crcssn);
       console.log("EMPSSN=",empssn);
       if(crcssn == empssn)
         {
          for(let r=0;r<result.length;r++){
            let crcdata = result[r];
            console.log(crcdata);
            for(let b=0;b<bodydata.length;b++) {
              let annual_income;
               console.log(bodydata[b]);
                let mergedata = Object.assign(crcdata, bodydata[b]);
                console.log("merge", mergedata);
                if (mergedata["IncomeFrequency"] == "Monthly") {
                  annual_income = (parseInt(mergedata["Income"]) * 12).toString();
                  console.log(annual_income);
                }
                else {
                  annual_income = mergedata["Income"];
                }
                let binary = {
                  "accounts_opened": mergedata["total_number_of_open_accounts"],
                  "bankruptcies": mergedata["total_number_of_bankruptcies"],
                  "collections": mergedata["total_number_of_collections"],
                  "credit_inquiries_last_6_months": mergedata["total_number_of_inquires_in_the_last_6_months"],
                  "past_due_accounts": mergedata["total_number_of_accounts_currently_past_due"],
                  "open_accounts": mergedata["total_number_of_open_accounts"],
                  "high_credit_limit": mergedata["total_credit_limit_amount"],
                  "annual_income": annual_income
                }
                console.log(binary);
                let arraybinary = Object.assign({},binary);
                console.log(arraybinary);
                binarydata.push(arraybinary);
                console.log(binarydata);

                let categorical = {
                  "bankruptcies_last_18_months": mergedata["count_of_bankruptcies_last_24_months"],
                  "credit_inquiries_last_6_months": mergedata["count_of_auto_loan_inquiries_last_9_months"],
                  "months_since_most_recent_inquiry": mergedata["total_number_of_inquires_in_the_last_6_months"],
                  "ninety_plus_delinquencies_last_18_months": mergedata["total_number_of_accounts_with_90180_day_delinquencies"],
                  "number_of_accounts_currently_30dpd": mergedata["total_number_of_accounts_with_3059_day_delinquencies"],
                  "open_credit_accounts": mergedata["total_number_of_open_auto_accounts"],
                  "pre_loan_debt_to_income": mergedata["total_amount_of_credit_debt"],
                  "total_current_balance": mergedata["total_account_balance"],
                  "total_high_credit_limit": mergedata["total_credit_limit_amount"],
                  "annual_income": annual_income
                }
                console.log(categorical);
                let arraycategory = Object.assign({},categorical);
                console.log(arraycategory);
                categoricaldata.push(arraycategory);
                let Linear = {
                  "bankruptcies_last_18_months": mergedata["count_of_bankruptcies_last_24_months"],
                  "credit_inquiries_last_6_months": mergedata["count_of_auto_loan_inquiries_last_9_months"],
                  "months_since_most_recent_inquiry": mergedata["total_number_of_inquires_in_the_last_6_months"],
                  "ninety_plus_delinquencies_last_18_months": mergedata["total_number_of_accounts_with_90180_day_delinquencies"],
                  "number_of_accounts_currently_30dpd": mergedata["total_number_of_accounts_with_3059_day_delinquencies"],
                  "open_credit_accounts": mergedata["total_number_of_open_auto_accounts"],
                  "pre_loan_debt_to_income": mergedata["total_amount_of_credit_debt"],
                  "total_current_balance": mergedata["total_account_balance"],
                  "total_high_credit_limit": mergedata["total_credit_limit_amount"],
                  "annual_income": annual_income
                }
                console.log(Linear);
                let arraylinear = Object.assign({},Linear);
                console.log(arraylinear);
                Lineardata.push(arraylinear);
            }
          }
         }
         break;
      }
  } 
  console.log(binarydata.length);
  console.log(binarydata);
  converter.json2csv(binarydata,(err,csv) => {
    if(err)throw err;
    console.log(csv);
    file.writeFileSync('/home/rita_gatistavam/Downloads/CSV/binarydata.csv',csv);
    console.log('File Written');
  })
  converter.json2csv(Lineardata,(err,csv) => {
    if(err)throw err;
    console.log(csv);
    file.writeFileSync('/home/rita_gatistavam/Downloads/CSV/lineardata.csv',csv);
    console.log('File Written');
  })
  converter.json2csv(categoricaldata,(err,csv) => {
    if(err)throw err;
    console.log(csv);
    file.writeFileSync('/home/rita_gatistavam/Downloads/CSV/categorydata.csv',csv);
    console.log('File Written');
  })
   next();
}
async function  uploadData(req,res,next){
let moduletype = sessionStorage.getItem('moduletype');
console.log(moduletype);

 req.params.id = sessionStorage.getItem('modelid');
 console.log(req.params.id);
 try {
  
  res.status(200).send({
    status: 200,
    timeout: 10000,
    type: 'success',
    text: 'Changes saved successfully!',
    successProps: {
      successCallback: 'func:window.createNotification',
    },
    responseCallback: 'func:this.props.reduxRouter.push',
    pathname: `/ml/models/${req.params.id}/training/historical_data_${moduletype}`,
  });
  
} catch (e) {
  periodic.logger.warn(e.message);
  res.status(500).send({ message: 'Error updating model type.', });
}

}```

Cannot understand your question, but I assume you want to get all the async request in one go.无法理解您的问题,但我假设您想在一个 go 中获取所有异步请求。

You can achieve this with Promise.all, all the results will be returned as an array, and all the request will run at the same time.您可以使用 Promise.all 来实现这一点,所有结果将作为数组返回,所有请求将同时运行。

const results = await Promise.all([asyncRequest1, asyncRequest2, asyncRequest3])

getting resulsts sequentially.依次得到结果。

await asyncRequest1();
await asyncRequest2();
await asyncRequest3();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM