sumitrathi
(Sumitrathi)
September 15, 2021, 3:43pm
1
I need to write a funtion for a get http request which I am using many places. I am trying to create async function with await but still got getting value in return. Can some one guide how to write the code for this.
data = get_price(url)
async function get_price(url) {
try {
const resp = await axios({
method: "GET",
url: url,
headers: {
"Content-Type": "application/json",
"Authorization": authorization
}
}).then(function(resp){
console.log(resp.data)
return resp.data
});
} catch(e) {
return "error";
}
}
danny
(Danny Roosevelt)
September 15, 2021, 5:37pm
2
Hi there – it looks like there’s a bit of mixup with promisifying your code. Below is a modification that should work for you, and in case you’re interested, I’d check this out for more info: Making asynchronous programming easier with async and await - Learn web development | MDN
async function get_price(url) {
try {
return await axios({
method: "GET",
url: url,
headers: {
"Content-Type": "application/json",
"Authorization": authorization
}
})
} catch(e) {
return "error";
}
}
1 Like
sumitrathi
(Sumitrathi)
September 16, 2021, 2:51am
3
Thanks Danny… Also when I added await with the function from where I am calling it, it worked
data = await get_price(url)