title: How to run request sequentially in a loop?
body: <p>This is a pseudo code of what I am trying to achieve. First I need to get a list of URLs from the request body then pass those URLs to request function (using request module) which will get the data from each url and then save those data to MongoDB. After all the requests are finished including saving data to the server only then it should send a response.</p>
  
  <pre><code>app.post('/', (req, resp) =&gt; {
  
      const { urls } = req.body;
  
      urls.forEach((url, i) =&gt; {
  
          request(url, function (err, resp, body) {
  
              if (err) {
                  console.log('Error: ', err)
              } else {
                  // function to save data to MongoDB server
                 saveUrlData(body);
                 console.log(`Data saved for URL number - ${i+1}`)
              }
          })
      });
  
      // Should be called after all data saved from for loop
      resp.send('All data saved')
  })
  </code></pre>
  
  <p>I have tried this code and of course the resp.send() function will run without caring if the request has completed. Using this code I get a result on the console like this: </p>
  
  <pre><code>Data saved for URL number - 3
  Data saved for URL number - 1
  Data saved for URL number - 5
  Data saved for URL number - 2
  Data saved for URL number - 4
  </code></pre>
  
  <p>I could write them in nested form but the variable <code>urls</code>can have any number of urls and that's why it needs to be in the loop at least from my understanding. I want the requests to run sequentially i.e. it should resolve 1st url and then second and so on and when all urls are done only then it should respond. Please help!</p>