Pausing a function call until an async call completes - javascript

I have a forward navigation function, which triggers an async API call on certain stages, where it is required that it does not proceed (move forward) until said API call is finished (it triggers a processor in the background required for the following stages).
My issue is that it continues to proceed, despite the call not yet being completed. I'm confused at to the best and most suggested way to implement this, and would be happy for any advice.
Code:
async postData(url = "", data = {}) {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
},
forwardTicketId(ticketId) {
const origin = new URL(window.location.href).origin;
const addr = `${origin}/current_ticket_id`;
this.postData(`${addr}`, {
data: ticketId,
});
},
goNext() {
if (this.isRequiredStage) { # this needs to complete before anything else runs
this.forwardTicketId(this.ticketId);
}
this.navGoNext();
},
How the goNext function is called:
<div class="level-right">
<TicketStepsNavButtons
#goPrev="goPrev"
#goNext="goNext"
/>
</div>

Use await in the calls too.
async postData(url = "", data = {}) {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
// you can return the response if you need it
return response;
},
forwardTicketId(ticketId) {
const origin = new URL(window.location.href).origin;
const addr = `${origin}/current_ticket_id`;
// return to chain the next promises, you can async/await instead if you don't care about the result
return this.postData(`${addr}`, {
data: ticketId,
});
},
async goNext() {
if (this.isRequiredStage) { // this needs to complete before anything else runs
// await here
await this.forwardTicketId(this.ticketId);
}
this.navGoNext();
},

Related

how to await value from another await variable

I cannot figure out how should I construct my code.
Basic info:
webhook (intercom) --> google cloud functions (await values) --> post message to slack.
Issue:
My code is working fine until I need to get an value from another await function and I am not sure how should I 'pause' the second await until the first one is complete.
Code:
// first function to get the information about agent
const getTeammateInfo = async function (teammate_id) {
try {
const response = await axios.get("https://api.intercom.io/admins/" + teammate_id, {
headers: {
'Authorization': "Bearer " + INTERCOM_API_AUTH_TOKEN,
'Content-type': "application/json",
'Accept': "application/json"
}
});
const { data } = response
return data
} catch (error) {
console.error(error);
}
};
// second function, which needs values from first function in order to find data
const slackID = async function (slack_email) {
if (slackID) {
try {
const response = await axios.get("https://api.intercom.io/admins/" + slack_email, {
headers: {
'Authorization': "Bearer " + SLACK_API_TOKEN,
'Content-type': "application/json",
'Accept': "application/json"
}
});
const { user } = response
return user
} catch (error) {
console.error(error);
}
}
};
It is used within the Google Cloud Function (
exports.execute = async (req, res) => {
try {
// map of req from intercom webhook
let {
data: {
item: {
conversation_rating: {
rating,
remark,
contact: {
id: customerId
},
teammate: {
id: teammateId
}
}
}
}
} = req.body
const teammateName = await getTeammateInfo(teammateId); // this works fine
const slackTeammateId = await slackID(teammateName.email) // this is where it fails I need to get the values from 'teammateName' in order for the function slackID to work
...
} catch (error) {
console.error(error)
res.status(500)
res.json({ error: error })
}
}
I have tried with Promise.all
const [teammateName, slackTeammateId] = await Promise.all([
getTeammateInfo(teammateId),
slackID(teammateName.email)
])
But I just cannot wrap my head around this how it should work.
Thank you.
// edit:
Code is okay, I just put the wrong API into the slackID function...
Thanks for double checking.
The problem with Promise.all() is that it fires both functions at the same time and waits until both are done, so you can't chain that way.
let teammateName
let slackTeammateId
getTeammateInfo(teammateId).then(r => {
teammateName = r
slackID(teammateName.email).then(r2 => {
slackTeammateId = r2
)}
);
then() method, on the other hand, waits until your method's return and then fires out everything in the callback function.

send post and get request on click using NEXT JS

i need to post and get my data when clicking on the same button [like write and show comment] , but when i click the button everything is going well but a request with 304 status code is running with infinite loop, can someone help ?
const addCommentHandler = (commentData) => {
axios({
url: `/api/comment/${eventId}`,
method: "post",
data: commentData,
headers: {
"Content-type": "application/json",
},
}).then((res) => {
const data = res.data;
console.log(data);
});
axios({
url: `/api/comment/${eventId}`,
method: "get",
}).then((res) => {
const data = res.data;
setComments(data.comments);
});
};
useEffect(() => {
addCommentHandler();
}, []);
It seems like You want to Post the Data and then want to get the Updated Comments.But you are creating Two Asynchronous Api Calls..
304 Status Code Means " The requested resource has not been modified since the last time you accessed it "
Please Refresh Cache and try Again..
const addCommentHandler = async (commentData) => {
// add Try Catch for Errors..
const responseData = await axios({
url: `/api/comment/${eventId}`,
method: "post",
data: commentData,
headers: {
"Content-type": "application/json",
},
})
const resData = await axios({
url: `/api/comment/${eventId}`,
method: "get",
})
setComments(resData.data.comments);
};
useEffect(() => {
// Pass CommentData as Params in addCommentHandler
addCommentHandler();
}, []);`

HTTP fetch info IN ORDER and add to array in the order specified

I have tried it all. I want to fetch from my server some data in a loop, and add the ressponses in an array in the order I run the for loop.
I am thinking the answer is in recursion, but tried it several times and failed.
I am using AXIOS:
let currentPhraseWordAssign = [];
function addPartOfSpeechAndWordPhrasesToFullScript () {
assignPartOfSpeechAndAddToPhraseArray(["phrase", "run"]).then(() => {console.log(currentPhraseWordAssign)});
}
async function assignPartOfSpeechAndAddToPhraseArray (phrase) {
if(currentPhraseWordAssign.length >= phrase.length) {
console.log(currentPhraseWordAssign);
currentPhraseWordAssign = [];
return;
}
let word = phrase[currentPhraseWordAssign.length];
axios({
method: 'get',
url: `http://localhost:9200/english_minus_verbs/_search`,
headers: {
'Content-Type': 'application/json'
},
data: {
_source: ["part_of_speech"],
query: {
term: {
word: word,
}
}
}
}).then((r) => {
try {
currentPhraseWordAssign.push({word: word, partOfSpeech: r.data.hits.hits[0]._source.part_of_speech});
}catch (e) {
currentPhraseWordAssign.push({word: word, partOfSpeech: 'verb'});
}
}).then(()=>{
assignPartOfSpeechAndAddToPhraseArray(phrase);
});
}
Maybe that code is completely wrong, it is anyway like the 7th time I write it... I tried with promises, async/await, sync, and now recursion...
You can run the axios calls in sequence (one after the other) like this:
async function lookupWords(arrayOfWords) {
let currentPhraseWordAssign = [];
for (let word of arrayOfWords) {
const data = await axios({
method: 'get',
url: `http://localhost:9200/english_minus_verbs/_search`,
headers: {
'Content-Type': 'application/json'
},
data: {
_source: ["part_of_speech"],
query: {
term: {
word: word,
}
}
}
});
currentPhraseWordAssign.push({word: word, partOfSpeech: r.data.hits.hits[0]._source.part_of_speech});
}
return currentPhraseWordAssign;
}
Or, you can run them in parallel and collect the results in order:
function lookupWords(arrayOfWords) {
return Promise.all(arrayOfWords.map(word => {
return axios({
method: 'get',
url: `http://localhost:9200/english_minus_verbs/_search`,
headers: {
'Content-Type': 'application/json'
},
data: {
_source: ["part_of_speech"],
query: {
term: {
word: word,
}
}
}
}).then(r => {
return {word: word, partOfSpeech: r.data.hits.hits[0]._source.part_of_speech};
});
}));
}
If you run them in parallel (which may finish sooner), you have to make sure that the target server will accept however many simultaneous requests as your array is long. Some servers will limit or reject too many simultaneous requests. To run semi-in-parallel where you have N requests in flight at the same time (how you would process a large array in parallel without too many requests in flight at once), you would use something like mapConcurrent() to control the execution.

Need to call Two APIs In Loop using node js

I have an array of ssn number and I have two api list in which I need to pass ssn number as request json so I need to call both api inside ssn loop so I pass ssn to json request during call both api but code is not work properly both api call at a time simulteniously, Where I need to call both api one by one.
Both API details and code are as follow
My Code:
let ssn = [460458524, 637625452, 453311896, 635285187, 455791630, 642348377, 463590491, 450730278, 641201851, 379965491];
async function getCRCDetails() {
ssn.forEach(function (item) {
if(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
}
})
}
request(CBCOptions, function (error, response) {
console.log(item);
console.log("CBCOPtion ", CBCOptions);
if (error) throw new Error(error);
result = (JSON.parse(response.body));
console.log("Result =", result);
CRCReport.push(result);
})
let EmployerInfoOptions = {
'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
}
})
}
request(EmployerInfoOptions, function (error, response) {
console.log(response.body);
})
}
Here I need to call API request one by one.Anyone Guide me please.
I prefer use async await method for this situation
you need install and require async and request-promise
after that :
const request = require("request-promise");
const async = require("async");
let ssn = [460458524, 637625452, 453311896, 635285187, 455791630, 642348377, 463590491, 450730278, 641201851, 379965491];
async function getCRCDetails() {
//like a forEache
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 EmployerInfoOptions = {
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 request(CBCOptions);
let EmployerInfoOptions = await request(EmployerInfoOptions);
console.log(resultCBCOptions)
console.log(EmployerInfoOptions)
//do pushing resultCBCOptions
//do pushing EmployerInfoOptions
} catch (error) {
console.log(error);
}
},
() => {
console.log("finished");
}
);
}
In Node the request methods that you are using are asynchronous. Meaning the runner (server) that runs the code does not wait for the request to finish and just continues to execute the next lines.
One thing that you can do is,
request.post(params).on("response", function(response) {
//....Do stuff with your data you recieve
// Make the next call here
request.post(params).on("response"), function() {
// Here you will have the second call's results
}
})
This ensures that both the API calls happen in order and only after the first one finishes.
Note:
The request library that you are using has been deprecated back in 2020. See https://github.com/request/request Hence, I would suggest you use other libraries like the standard https or http library that is shipped with node or you can use axios.
If you use a forEach loop without awaiting the results, you'll execute them all at the same time. Moreover, request library is kind of old and you need to convert its functions to return a promise.
Here's how I would do it.
const ssn = [1,2,3,4];
function download(item) {
return new Promise(function(resolve, reject) {
let options = {}; // construct your request
request(options, function (error, response) {
if(error) {
return reject(error);
}
resolve(response);
})
}
}
ssn = ssn.map(async function(item) {
let res = await download(item);
// process the result
return res;
});
You can also use the Bluebird library or get another client library such as got or axios.

Get response from axios with await/async

I'm trying to get JSON object from axios
'use strict'
async function getData() {
try {
var ip = location.host;
await axios({
url: http() + ip + '/getData',
method: 'POST',
timeout: 8000,
headers: {
'Content-Type': 'application/json',
}
}).then(function (res) {
console.dir(res); // we are good here, the res has the JSON data
return res;
}).catch(function (err) {
console.error(err);
})
}
catch (err) {
console.error(err);
}
}
Now I need to fetch the res
let dataObj;
getData().then(function (result) {
console.dir(result); // Ooops, the result is undefined
dataObj = result;
});
The code is blocking and waits for the result, but I'm getting undefined instead of object
This seems to be one of those cases where async/await doesn't buy you much. You still need to return a result from the async function, which will return a promise to the caller. You can do that with something like:
async function getData() {
try {
let res = await axios({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'get',
timeout: 8000,
headers: {
'Content-Type': 'application/json',
}
})
if(res.status == 200){
// test for status you want, etc
console.log(res.status)
}
// Don't forget to return something
return res.data
}
catch (err) {
console.error(err);
}
}
getData()
.then(res => console.log(res))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
But in this example, since you don't need to do much in the actual function with the result, you're probably better off just returning axios's promise:
function getDataPromise() {
return axios({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'get',
timeout: 8000,
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.data)
.catch (err => console.error(err))
}
getDataPromise()
.then(res => console.log(res))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
It is not what you would like to hear but
Async/Wait works on the principle "Whatever Happens in Vegas - Stays in Vegas". It means you could not pass benefits of using blocking IO calls outside of async block.
If you want to use async/await to create some kind of blocking IO call it would not work unless a block caller is also inside an async function what is not normally the case.
async/wait is only good if you want to have a long chain of IO calls but entire chain still MUST be non-blocking. Individual calls inside chain might be blocking but full chain not.
Example
async fn(url) { //this is a non blocking function
let res = await axios.get("http://jsonservice1"); //blocking but only inside this function
let res2 = await axios.get(url+'?s='+res.data);//res.data is resolved already
return res2; //this how it returns results but it will not be resolved until .then is called what is effectively a callback
}
fn("google.com").then(R=>console.log('sorry I am not blocking '+R.data));
Coming from ajax, I prefer modular approach. Data to be sent, function on success and function ‎on fail are separate from function using axios. Bellow sample code fetch user email against ‎user name form node.js and mysql at the backend. ‎
HTML: <button onclick=" testaxios();">TestAxios</button>‎
JS in browser:
var data = {
username: "myusername"
}
async function testaxios() {
try {
let res = await axios({
method: 'POST',
data: data,
url: '/testmysql',
});
if (res.status == 200) {
success(res);
};
}
catch (error) {
fail(error);
};
}
function success(res) {
console.log(res.data[0][0].email);
}
function fail(error) {
console.log(error);
}
JS in nodeJS at backend:
app.post("/testmysql", async function (req, res) {
try {
let usrname = req.body.username;
let em = await pool.query("SELECT email FROM users WHERE username = ?", usrname);
res.send(em);
} catch (err) {
console.log(err);
} });

Categories