This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 months ago.
I'm trying to perform an axios get request.
axios
.get("http://10.10.0.145/api/session", {
headers: {
'Cookie' : user_cookie
}
},
)
.then(res => {
result = res.data;
id_user_intervention = res.data.id;
console.log(id_user_intervention); //IS NOT UNDEFINED
})
.catch(error => {
console.error(error)
})
console.log(id_user_intervention); //IS UNDEFINED
I need to use id_user_intervention outside the axios request. I assign res.data.id to id_user_intervention, but this variable is undefined outside the axios request...how can I solve this problem?
First of all, it's better you learn async/await on javascript. Then, try the following solution:-
const testFunction = async () => {
let id_user_intervention = null;
try {
const response = await axios.get("http://10.10.0.145/api/session", {
headers: {
'Cookie': user_cookie
}
})
id_user_intervention = response.data.id;
} catch (err) {
console.error(err);
}
return id_user_intervention;
}
const anotherFunction = async () => {
const data = await testFunction();
console.log(data);
}
Hope it will work properly.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How can I access the value of a promise?
(14 answers)
async/await implicitly returns promise?
(5 answers)
Why is my asynchronous function returning Promise { <pending> } instead of a value?
(9 answers)
What are asynchronous functions in JavaScript? What is "async" and "await" in JavaScript?
(2 answers)
Closed 4 months ago.
So I have a function that calls my API:
const trackPurchase = async (customerId, unitsPurchased) => {
const response = await fetch("http://localhost:5000/purchases", {
method: "POST",
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
"customerId": customerId,
"unitsPurchased": unitsPurchased
})
})
return await response.text()
};
module.exports = { trackPurchase };
In another file I call the above function:
const trackPurchases = async () => {
try {
const units = await trackPurchase (123, 1)
return units
} catch (error) {
console.log("ERROR ",error)
}
};
console.log(
"trackPurchases ",
trackPurchases ()
)
Logging the result I get a promise. Meanwhile, the request succeeded and the database is updated.
What am I missing? Why isn't the promise resolving?
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How can I access the value of a promise?
(14 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed last year.
so I have class for data object, I'm trying to define one property where I fetch it's value from api
this is how the class looks like:
export default class User extends Base {
....
constructor(packet: Packet) {
....
this.card = this.get_user_card() // showing undefined
}
get_user_card(): Card {
this.rest.api(...).get().then((res: any) => {
console.log(res.data); // return the card data
return res.data;
})
}
}
it's showing undefined when I set to card properties outside the function
I even tried this but this one showing Promise <pending> I can't use await inside constructor
return this.rest.api(...).get().then((res: any) => {
return res.data;
})
and this but it's showing undefined for both and if I make it asynchronous it will return promise pending for the this.card
const res = this.rest.api(...).get()
console.log(res.data) //undefined
return res.data; //undefined too
tried this one too and doesn't work
this.rest.api(...).get().then((res: any) => {
this.channel = res.data; //not working
// even assign
Object.assign(this, { card: res.data }); //not either
})
but console logging inside their .then is working. can someone help me or have other solution?
This question already has answers here:
await is only valid in async function
(14 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
In a file called getData.js , I wrote the following code
module.exports = async function (page, id) {
const options = {
...
};
axios
.request(options)
.then((response) => {
myData = JSON.stringify(response.data);
return myData;
})
.catch((error) => {
console.error(error);
});
};
Now in my main index.js file, I imported the above module then I have this snippet,
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
let finalData = await getData(myPage, myID);
res.end(finalData);
});
When I run this node crashes and I get this error
SyntaxError: await is only valid in async functions and the top level bodies of modules
How do I make my code to work? I thought of using async-await becuase response.data is very big, but clearly I don't understand async-await functions fully. In the external module, If I try to return myData outside the .then block and also don't use async-await, then I get undefined finalData.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I've a get route in Nodejs. I'm accessing data from the database and looping through that data. I've a fetch twitch API request inside that loop which is using an attribute from that data. I've to filter the data in a way that if it the response is null then it should ignore it and if there is any data, it should append that into an array. Then at the end, it should return that array which have filtered data. But the problem is that it is returning empty array even though the data is coming from the API. I think this is the variable scope issue but I don't know how should I resolve it.
Following is my code:
router.get("/getstreams", async (req, res) => {
var arr = [];
await UserStreams.find().then(async (allStreams) => {
console.log(allStreams[0].user_id);
const a = allStreams.map(async (data) => {
return await fetch(`https://api.twitch.tv/kraken/streams/${data.user_id}`, {
headers: {
Accept: "application/vnd.twitchtv.v5+json",
"Client-ID": "yfzf3ux4gltxrcnentffrfvmlg7cwx",
Authorization: "Bearer xbbxf3cbtuwz4i5gkekxjb338p28yr",
},
method: "GET",
})
.then(async (res) => {
return await res.json();
})
.then(async (json) => {
return await (json !== null && arr.push(json));
});
});
console.log("array = ", arr);
console.log("array2 = ", a);
res.send(a);
});
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm working on two functions about my project. First function is async function:
async function abc(params) {
(...)
var sdata = JSON.stringify(params);
fetch(...)
.then(response => response.json())
.then(data => {
/*do something*/
})
.catch(err => {
/*err do something*/
})
}
Second function is:
function xyz (param){
irrevelantFunction(param);
}
I tried to execute this two functions like below:
abc(params).then(xyz(param));
but it doesn't work. How can I solve this problem? Many thanks for your precious support.
If you are using async then you can avoid .then, kindly see the sample snippet code
async function abc(params) {
var sdata = JSON.stringify(params);
try{
const response = await fetch(...)
if(response.ok){
const body = await response.json();
xyz(body)
return
}
const cusotomError = {
message: 'something went wrong'
}
throw customError
}catch(error){
console.log(error) // you can show error to ui logic
}
function xyz (param){
irrevelantFunction(param);
}