Following is the code where I use async await to fetch a token, which is the used to make another request.
But the issues is that even though I'm doing it as one by one async await request, the token is not getting defined before the second async call is made.
So I'm getting a big fat error.
try {
const access = await superagent
.post("https://token-link.com/token")
.send(
"apikey=" + API_KEY
)
.set("Content-Type", "application/x-www-form-urlencoded")
.set("Accept", "application/json");
const token = access.body["access_token"];
// console.log(token) -- > here I'm doing a console log and I'm being able to see the token.
// But when the following request is made right after the above one, I'm getting an error.
const report = await superagent
.post(
"https://another-link/api/v2/data"
)
.set("Accept", "application/json")
.set("Authorization", "Bearer " + token)
.set("Content-Type", "application/json;charset=UTF-8")
.send(
JSON.stringify(data)
);
res.send(report);
// also when I do a console.log(report.body.data) --> then also I'm getting an error...
} catch (e) {
res.status(400).json({ error: e });
}
Now If I do a curl request and store the token as a constant before making the second request, then the error is gone.
So I assume that the first request is not fullfilled before the second one is made.
Can someone help?
try {
const token = "eyJraWQiOiIyMDIxMDQyMDE4MzYiLCJhbGciOiJSUzI1NiJ9.eyJpYW1faWQiOiJJQk1pZC01NTAwMDlFUzY5IiwiaWQiOiJJQk1pZC01NTAwMDlFUzY5IiwicmVhbG1pZCI6IklC"
// If the token is stored as a constant then there is no error.
const report = await superagent
.post(
"https://another-link/api/v2/data"
)
.set("Accept", "application/json")
.set("Authorization", "Bearer " + token)
.set("Content-Type", "application/json;charset=UTF-8")
.send(
JSON.stringify(data)
);
res.send(report);
} catch (e) {
res.status(400).json({ error: e });
}
IS my async await working as expected or am I missing something?