Async/Await Method Issue - javascript

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/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.
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();

Related

How do I need to collect my data in the object for post request?

I just want to send request, but in the end of function my object is{img:'',text: ''}.
I expect to get .jpg file name in obj.img and text inside .txt file in obj.text. So here we go:
Maybe it's something about scope. I don't know.
const path = require('path');
const fs = require('fs');
const request = require('request');
const axios = require('axios');
let shortcode = '';
async function getData() {
const obj = {
img: '',
text: '',
};
await fetch('http://127.0.0.1:8000/api')
.then(response => response.json())
.then(data => (shortcode = data[data.length - 1].shortcode));
fs.readdir(
`path/${shortcode}`,
(err, data) => {
if (err) {
throw err;
}
data.forEach(file => {
if (path.extname(file) === '.jpg') {
obj.img = file;
} else if (path.extname(file) === '.txt') {
fs.readFile(
`path/${shortcode}/${file}`,
'utf-8',
(err, data) => {
if (err) {
throw err;
}
obj.text = data;
console.log(data);
},
);
}
});
},
);
console.log(obj);
await fetch('http://127.0.0.1:8000/instaData', {
method: 'POST',
body: JSON.stringify({
img: obj.img,
text: obj.text,
}),
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
});
}
getData();

How to delete a forge bucket from Autodesk forge

I am successfully creating Bucket and uploadFile successfully using sample.
https://github.com/Autodesk-Forge/forge-extensions
I added the delete function
But when I delete the bucket I get an error.
----oss.js---
router.post('/buckets', async (req, res, next) => {
let payload = new PostBucketsPayload();
payload.bucketKey = config.credentials.client_id.toLowerCase() + '-' + req.body.bucketKey;
payload.policyKey = 'transient'; // expires in 24h
try {
// Create a bucket using [BucketsApi](https://github.com/Autodesk-Forge/forge-api-nodejs-client/blob/master/docs/BucketsApi.md#createBucket).
//Bucket createBucket(postBuckets, opts, oauth2client, credentials)
await new BucketsApi().createBucket(payload, {}, req.oauth_client, req.oauth_token);
res.status(200).end();
} catch(err) {
next(err);
}
});
router.delete('/buckets/delete', async (req, res, next) => {
const encoded_bucketKey = encodeURI(req.bucketKeyID);
try {
// Delete a bucket using
await new BucketsApi().deleteBucket(encoded_bucketKey, req.oauth_client, req.oauth_token);
res.status(200).end();
} catch(err) {
next(err);
}
});
-----------ForgeTree.js -------
function createNewBucket() {
var bucketKey = $('#newBucketKey').val();
var policyKey = $('#newBucketPolicyKey').val();
jQuery.post({
url: '/api/forge/oss/buckets',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': bucketKey, 'policyKey': policyKey }),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
$('#createBucketModal').modal('toggle');
},
error: function (err) {
if (err.status == 409)
alert('Bucket already exists - 409: Duplicated')
console.log(err);
}
});
}
function deleteBucket() {
var node = $('#appBuckets').jstree(true).get_selected(true)[0];
switch (node.type) {
case 'bucket':
jQuery.ajax({
url: '/api/forge/oss/buckets/delete',
type:'delete',
contentType: 'application/json',
data: JSON.stringify({ 'bucketKey': node.text , 'bucketKeyID' : node.id}),
success: function (res) {
$('#appBuckets').jstree(true).refresh();
},
error: function (err) {
alert('Bucket delete error:')
console.log(err);
}
});
break;
}
console.log("Delete Bucket=%j", node)
}
I checked the config.js in the sample, it doesn't include bucket:delete scope when acquiring the token by default. Have you added the scope in your code?
Also inside delete route,
const encoded_bucketKey = encodeURI(req.bucketKeyID);
should be
const encoded_bucketKey = encodeURI(req.body.bucketKeyID);
Otherwise, you'll have undefined as encoded_bucketKey.

I cannot call an API inside for loop using nodejs

I'm trying to call an API inside a for loop using Nodejs,when the code is executed only the last element is called by the API:
the code :
var array=[12,124,852,256,5677,256,5679,2546,567,28,574]
for(var i=0;i<array.length;i=i++){
var b = array.splice(i,3);
const parameters1 = {
Ids: b.toString(),
limit: 45,
}
const get_request_args1 = querystring.stringify(parameters1);
const options1 = {
method: 'GET',
host: "host",
port: '443',
path: path + '?' + get_request_args1,
headers: {
'Accept': 'application/json',
'authorization': `Bearer ${token}`,
'Accept-Encoding': 'identity',
}
}
var req = http.request(options1, (res) => {
context.log("API CALL...",i);
var body = "";
var pages = 0;
var offset = [];
var limit = 100000;
res.on("data", (chunk) => {
body += chunk;
});
res.on("end", () => {
const obj = JSON.parse(body);
//context.log('total pages 3 :', pages);
context.log('total :', obj.total);
context.res = { body: offset };
context.done();
});
}).on("error", (error) => {
context.log('ERROR :', error);
context.res = {
status: 500,
body: error
};
context.done();
});
}
when this code is executed only the last element in the array executed by the API, what I'm looking for is executing the api for each iteration of the for loop, any helps please ?
Not sure how your full function looks like, but you should build your function as fully structured as async-await.
And also you could use map function instead of for.
const yourFunction = async () => {
try {
const array = [12,124,852,256,5677,256,5679,2546,567,28,574];
const requests = array.map(async (item) => {
...
var req = await http.request(async options1, (res) => {
context.log("API CALL...",i);
...
});
await Promise.all(requests);
...
} catch (err) {
console.error(err);
}
}

here i am getting await can only use inside async function error but i am using async in my function

const express = require('express')
const router = express.Router()
const request = require('request')
const endponits = require('../sub/endpoints')
const status = require('../sub/status')
const db = require('../util/db')
const util = require('../util/util')
const CryptoJS = require('crypto-Js')
const fetch = require('node-fetch')
const notify = router.post('/', async (req, res) => {
console.log(req.body);
const CLIENT_SECRET = process.env.PAYMENT_TEST_SECRET_KEY;
// const amt = req.body.orderAmount;
let postData = {
oid: req.body.orderId,
amt: req.body.orderAmount,
rsn: req.body.txMsg,
tt: req.body.txTime
}
let signData =
req.body.orderId +
req.body.orderAmount +
req.body.referenceId +
req.body.txStatus +
req.body.paymentMode +
req.body.txMsg +
req.body.txTime;
// const postData = {
// oid: req.body.orderId,
// amt: req.body.orderAmount,
// refId: req.body.referenceId,
// sts: req.body.txStatus,
// pm: req.body.paymentMode,
// tm: req.body.txMsg,
// tt: req.body.txTime,
// signature: req.body.signature
// }
// var keys = Object.keys(postData);
// var signature = postData.signature;
// keys.sort();
// var signatureData = "";
// keys.forEach((key) => {
// if (key != "signature") {
// signatureData += postData[key];
// }
// });
// var computedSignature = crypto.createHmac('sha256', CLIENT_SECRET).update(signatureData).digest('base64');
// if (computedSignature == signature) {
let sdata = util.computeSign(signData);
if (sdata == req.body.signature) {
let data = {
sts: 'Inprogress',
//'so.pm': req.body.paymentMode || '',
//'so.refId': req.body.referenceId || '',
//uAt: Date.now()
}
db.getref(postData.oid, 'txn', successFunc => {
if (successFunc) {
const txnid = successFunc.id;
const appId = successFunc.appid;
db.updateById(
txnid,
data,
'txn',
success => {
if (success) {
let payload = {}
payload['txnId'] = txnid;
let PAYOUT_URI = 'https://ap.moneyorder.ws/api/v1/payout/test'
let Token = 'ceobrtoen'
let options = {
method: 'POST',
body: JSON.stringify(payload),
headers: {
appid: appId,
token: Token
}
}
try {
let response = await fetch(PAYOUT_URI, options)
let tokenres = await response.json()
//here we call payout Api
// let payload = { txnId: txnid };
// let Token = 'ceobrtoen';
// const PAYOUT_URI = 'https://ap.moneyorder.ws/api/v1/payout/test
// let options = {
// method: 'POST',
// url: PAYOUT_URI,
// body: JSON.stringify(payload),
// headers: {
// appid: appId,
// token: Token
// }
// }
// request(options, (err, response, body) => {
// if (err) {
// res
// .status(status.HTTPS.SERVER_ERROR)
// .json({ msg: 'Something went wrong.' })
// } else {
// let data = JSON.parse(body)
// console.log(data);
// console.log(options.body);
if (tokenres && tokenres.status === 'SUCCESS') {
// 3. update txn record
let updateObj = {
sts: 'Success',
}
db.updateById(
txnid,
updateObj,
'txn',
success => {
if (success) {
cosole.log("payout updated")
} else {
res.status(status.HTTPS.SERVER_ERROR).json({
data: null,
msg: 'Something went wrong at our end.',
success: false
})
}
},
err => {
res.status(status.HTTPS.SERVER_ERROR).json({
data: null,
msg: 'Something went wrong at our end.',
success: false
})
}
)
} else {
res.status(status.HTTPS.SERVER_ERROR).json({
data: null,
msg: "ERROR 1",
success: false
})
}
} catch (error) {
res.status(status.HTTPS.SERVER_ERROR).json({
data: null,
msg: 'Something went wrong at our end.',
success: false
})
}
// })
}
},
err => {
res
.status(status.HTTPS.BAD_REQUEST)
.json({ success: false, msg: 'error 404', data: null })
}
)
} else {
res
.status(status.HTTPS.BAD_REQUEST)
.json({ success: false, msg: "empty response" })
}
})
} else {
console.log(signData)
console.log(sdata)
}
})
module.exports = router
here I am using async and await but I am getting await only can be used inside an async function where I am wrong in this I am trying to hit other API but I am not getting success.i have also use request module instead of node-fetch but it is not working . can anybody tell me where I am wrong.......................................................................................................................................................
The success function of your db.updateById() isn't async, so you can't use await inside of it.
Also, consider abstracting those callback-style db functions, wrapping them in promises. That way, you can use async-await on the main flow of your application rather than nesting callbacks.
Please note you are doing an await inside success callback function of db.updateById()
Which should be async. Try this.
.
db.updateById( txnid,data, 'txn',
async (success) => {
},
async (err)=> {
}
}
if it dosent work and you can not make the success callback async for some reason
just return another function in the callback and make that async
db.updateById( txnid,data, 'txn',
success => {
(async () => {
})()
},
err => {
}
}

Calling Facebook Messenger API in a synchronous fashion

I'm using the Facebook Messenger API to create a very basic chatbot. I want to be able to send a series of messages in individual bubbles. However, when I call the API multiple times in the same function. I can't be sure which message will show first. How can I use async/await functionality to correctly order the messages?
Function call initially:
const getStartedProcess = async(formattedText,senderID) => {
const firstMessage = await sendTextMessage(senderID,"First message");
const secondMessage = await sendTextMessage(senderID,"Second message");
const thirdMessage = await sendTextMessage(senderID,"Third message");
}
Helpers:
const sendTextMessage = async(recipientId, messageText) => {
//format message correctly
const sent = await callSendAPI(messageData);
return 0;
}
const callSendAPI = async(messageData) =>{
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
//Proccess
return 0;
});
}
How about this:
const sendTextMessage = (recipientId, messageText) => {
return new Promise((resolve, reject) => {
//format message correctly
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: PAGE_ACCESS_TOKEN},
method: 'POST',
json: messageData
}, (error, response, body) => {
if (error) {
reject(error);
} else {
resolve(response);
}
});
})
}
const getStartedProcess = async(formattedText, senderID) => {
try {
const firstMessage = await sendTextMessage(senderID, 'First message');
const secondMessage = await sendTextMessage(senderID, 'Second message');
const thirdMessage = await sendTextMessage(senderID, 'Third message');
} catch (error) {
console.log(error);
}
}

Categories

Resources