title: NodeJs function inside forEach loop need to complete before go to next item
body: <p>I have a Nodejs script, where it's detail look like below :</p>
  
  <p>1) it requests to API to get a list of city, it will get JSON array. using this array, I do looping using <code>forEach</code>. </p>
  
  <p>2) at each iteration (2nd loop), I do request again to API to get details (about 100 rows) and insert it into <code>mysql</code> database.</p>
  
  <p>my question, how to make the function inside the first loop (<strong>where to get the list of city</strong>) wait to complete before going to next item (city). I want to make a loop sequential with delay.</p>
  
  <p>my source code :</p>
  
  <pre><code>const request = require('request');
  var moment = require('moment');
  var mysql = require('mysql');
  
  var a = moment('2019-04-01');
  var b = moment('2019-04-06');
  const sleep = (waitTimeInMs) =&gt; new Promise(resolve =&gt; setTimeout(resolve, waitTimeInMs));
  
  function timer(ms) {
   return new Promise(res =&gt; setTimeout(res, ms));
  }
  
  var connection = mysql.createConnection({
      host : 'localhost',
      user : 'user1',
      password : 'password',
      database : 'local'
  });
  
  async function getURL(id_city,dates) {
  
      var url = 'https://localhost/api/format/json/schedule/city/'+id_city+'/date/'+dates;    
      request(url, { json: true }, (err, res, body) =&gt; {
        if (err) { return console.log(err); }
        // console.log(body.status);
        var item1 = body.schedule.data.item1;
        var item2 = body.schedule.data.item2;
  
        connection.connect();
        connection.query('INSERT INTO schedule (city,item1,item2) values ("'+id_city+'","'+task1+'", "'+task2+'")', function (error, results, fields) {
           if (error) throw error;
        });
        // connection.end();    
      });
  }
  
  
  async function getDate(id_city)
  {
      var end;
      for (var m = moment(a); m.isBefore(b); m.add(1, 'days')) {
          getURL(id_city,m.format('YYYY-MM-DD'));
          await timer(1000); //making delay           
      }
  }
  
  async function main () {    
      var url = 'https://localhost/api/format/json/list_city';
      connection.connect();
      request(url, { json: true }, (err, res, body) =&gt; {
        if (err) { return console.log(err); }
  
            var list_city = body.city; //this is an array
            var counter = 0;
            list_city.forEach(function(city){
                getDate(city.id, function(){
  
                });//i need this to complete before go to next city
  
            });
      });//end request url
  }
  
  main();
  </code></pre>
  
  <p>my expectation (sequential) :</p>
  
  <pre><code>city1
  insert item a done...
  insert item b done...
  city2
  insert item a done...
  insert item b done...
  insert item c done...
  city3
  ...
  </code></pre>