You can't mix plain callbacks with promises and have any hope in controlling the flow. Your functions such as geo.geocode()
and db.query()
do not return a promise when you pass them a callback and thus await
does nothing useful. Instead, you need to use the promise version of those functions or create a promisified version if one doesn't already exist.
If you use the beta version of the geocode library that supports promises and you use a version of your sql library that supports promises, then you would write your code like this:
async function functionName() {
//variables and such
for (let i = 0; i < results.length; i++) {
let geoData = await geo.geocode('mapbox.places', address);
await db.query(`INSERT INTO table (col1, col2, col3) VALUES($1, $2, $3) ON CONFLICT DO NOTHING`, ["default", val2, val3]);
}
}
But, since this sql statement is the same no matter what iteration of the loop you're doing, there must be some code missing here that uses the geoData
.
If you don't have access to the versions of geo.geocode
and db.query
that support promises, then you can manually promisify individual methods yourself like this:
const util = require('util');
const geo.geocodeP = util.promisify(geo.geocode);
const db.queryP = util.promisify(db.query);
async function functionName() {
//variables and such
for (let i = 0; i < results.length; i++) {
let geoData = await geo.geocodeP('mapbox.places', address);
await db.queryP(`INSERT INTO table (col1, col2, col3) VALUES($1, $2, $3) ON CONFLICT DO NOTHING`, ["default",
val2, val3
])
}
}
Keep in mind that none of this makes the function "wait" before returning. The function will still return a promise immediately when it hits the first await
and the caller will have to use that promise with await
or .then()
to get the eventual results from the function. What this allows you to do though, is sequence your asynchronous operations in your for
loop so they happen in sequence where one asynchronous operation waits for the prior to complete before the next runs.