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; }}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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); } } }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0