I'm currently having problems with the async/await Syntax. And for the last 2 days, I'm trying to find out why and finally decided to ask.
I'm trying to run a cron function(test) that calls an async function that connects to a database and tries to find new information regarding each entry with a 3rd party API.
Each function works on its own but when combining them they don't run in the correct order and the first function skips the await statement at the first row.(still executes it)
Output looks like the following(undefined -> DB entries -> api results)
The corret should look like (DB entries -> api results -> final results)
async function test() {
var db = await checkfornewdata() // executes
console.log(db) //skips line one and returns undefined as it didnt get its value
}
async function checkfornewdata()
{
var state = `SELECT * FROM users`;
var users= []
var newusers
console.log('Get connection ...');
connection.query(state , async function (err,result) {
if(err) throw err;
users= result
console.log('Query Result')
console.log(result) //works without problems
for (var i in result){
var checknew= await 3rdpartyapi.getusers(i.id );
if (i.joinDate> checknew.joinDate){
newusers.push(i);
}
console.log('New entries:')
console.log(newusers)
connection.end()
return newusers;
}
async function getusers(id)
{
var joinDate;
if (typeof(id) !== 'undefined'){
console.log("getting joinDate of " id)
await 3rdpartyapi.getUser(id).then(User => {
joindate= User.joinDate;
console.log(joinDate) //last output i recieve
})
.catch((err) => {
console.log(err)
return err;
})
return joinDate;
}}
CodePudding user response:
In your checkfornewdata
function, you're mixing promises and callbacks. In its current form your function returns before the call to the database finishes. (that's why console.log(db)
returns undefined
).
To fix this, you can use a mysql driver that supports promises (like mysql2) or rewrite your function like this:
function checkfornewdata() {
// ...
return new Promise((resolve, reject) => {
connection.query(state , async (err, result) => {
if (err) {
return reject(err);
}
// ...
resolve(newusers);
}
}
}
CodePudding user response:
You need to wait in for loop!
Try to add await
after for
statement like:
for await (var i in result){
var checknew= await 3rdpartyapi.getusers(element.id );
if (element.joinDate> checknew.joinDate){
newusers.push(element);
}
}