Reputation: 3562
I have this post route:
app.post("/new", async (req, res) => {
const Lob = require("lob")({ apiKey: keys.LOB_API });
let toAddress = await lobFuncs.toAddress(req.body.addrLine1, Lob);
console.log("test");
});
The toAddress() function looks like this:
toAddress: async (address, Lob) => {
await this.parseGoogleCiv(address, obj => {
console.log(obj);
});
},
parseGoogleCiv: async (address, callback) => {
address = address
.trim()
.split(" ")
.join("%20");
let URL = "some long URL"
await request(URL, function(err, res) {
if (err) {
console.log(err);
} else {
let body = JSON.parse(res.body);
callback(body);
}
});
}
But this is my output...
test
body
The "test" output should come after the body output.
Question: What's going on here? To the best of my knowledge I think I did all the async/awaits correctly seeing as I'm not getting an promise errors. Any ideas?
Upvotes: 3
Views: 3821
Reputation: 138234
The problem is that you basically await nothing in your parseGoogleCiv function. May do:
parseGoogleCiv: async (address) => {
address = address
.trim()
.split(" ")
.join("%20");
let URL = "some long URL"
try {
return JSON.parse(
(await new Promise((resolve,rej) => request(URL, function(err, res) {
if(err) return rej(err);
resolve(res);
}))).body
);
} catch(err){
console.log(err);
}
}
This is probably more elegant if you use the promisified request version:
parseGoogleCiv(address){
address = address
.trim()
.split(" ")
.join("%20");
const url = "someurl";
return request(url)
.then(res => JSON.parse( res.body ))
.catch( err => console.log(err));
}
Upvotes: 4