sachin murali
sachin murali

Reputation: 489

Await is not working for function call in nodejs?

I have a function named looper2(), which is accepting an array of data, and im trying to get the id of each data from mysql database.All is working fine, but my nodejs is not waiting for the function, when its still represent await.

var noloop = [];
noloop = await looper2(json_array1);
console.log("db id returns",noloop)

console.log("no loop",noloop[0]); //im getting this undefined

function looper2(){
    return new Promise(function(resolve, reject) {
        // Do async job
        for(var i=0;i<json_array1.length;i++){
            var sl =  "select id from json where name ="+db.escape(json_array1[i]);
            db.query(sl, function(err,result) {
                if (err) throw err;
                console.log("individual id:", result)
                noloop.push(result)
            });
           }
           resolve(noloop)
    });

}

Upvotes: 2

Views: 200

Answers (2)

narayansharma91
narayansharma91

Reputation: 2353

You can't use await without async function. So, you have to create a self-executable function to use await like below. And if you are using promise inside a loop there is promise.all function available, you can use to resolve all pending promises.

(async () => {
   var noloop = [];
   noloop = await looper2(json_array1);
   console.log(noloop);
})();

function async looper2(){
const promises = [];
 for(var i=0;i<json_array1.length;i++){
     var sl =  "select id from json where name ="+db.escape(json_array1[i]);
     db.query(sl, function(err,result) {
        if (err) throw err;
             promises.push(new Promise(result));
         });
      }
   return Promise.all(promises)
}

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281676

The problem is that in looper2 function you resolve immediately after the forLoop and don't wait for the db queries to complete. You should instead resolve after the db queries have all completed

function looper2(){
       return new Promise(function(resolve, reject) {
        // Do async job
        for(var i=0;i<json_array1.length;i++){
            var sl =  "select id from json where name ="+db.escape(json_array1[i]);
            db.query(sl, function(err,result) {
                if (err) throw err;
                console.log("individual id:", result)
                noloop.push(result)
                if(noloop.length == json_array1.length) {
                     resolve(noloop)
                }
            });
        }
    });
}

Upvotes: 2

Related Questions