Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript - Async/Await Method Issue

I am working on MERN Stack Application(Mean,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 place my code here :

mlrouter.js

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

MlController.js

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

    let loanboardapi = " ", dealersocket = " ";
    loanboardapi = {
      url: "https://loanboard.houstondirectauto.com/api/User/[email protected]&password=test@123",
      method: "GET"
    };
    dealersocket = {
      url: 'https://idms.dealersocket.com/api/authenticate/[email protected]&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.', });
}

}```

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Cannot understand your question, but I assume you want to get all the async request in one 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.

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

getting resulsts sequentially.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...