On Wednesday, October 25, 2017 at 7:38:37 AM UTC+2, [email protected] 
wrote:
>
> Here is my code. Its a simple one
>  for(var a=0; a<dResponse.length;a++ ){
>         var dId = dResponse[a].dId;
>         console.log('dId-->' +dResponse);
>           var dUrl = url?id=' + dId;
>           console.log('Url:'+dUrl);
>     }
> Every time it returns the same url.
>
>>
>>

You didn't show the whole code - what's in dResponse array? But, your title 
says "Synchronous for loop", depending on your node version, here's a 
simple example:

const request = require('request');

function callRemoteApi(url) {
  return new Promise((resolve, reject) => {
    console.log('Fetching', url);
    request(url, (err, res) => {
      if (err) {
        return reject(err);
      }
      console.log('Got', url);
      const result = JSON.parse(res.body).url;
      resolve(result);
    });
  });
}
async function runTest() {
  const urls = [
    'https://httpbin.org/delay/5',
    'https://httpbin.org/delay/1',
    'https://httpbin.org/delay/3',
  ];
  console.log('Urls ready.');
  let promises = [];
  for (let url of urls) {
    promises.push(callRemoteApi(url));
  };
  console.log('Promises ready.');
  await Promise.all(promises.map(async promise => console.log('Result of 
promise:' + await promise)))
    .then(() => console.log('All done.'));
}

runTest();

Now, if you run this code, it'll show you how things are working.

So the for loop example is indicative of potential issues with sync for 
loops. It takes an url, *waits* for it to return, and then goes on to the 
next.
Now, the other example works much better: we execute all promises 
immediately, in parallel. And as they come back, we get the results logged 
immediately.

Not sure how applicable this is to your situation, but if you post more 
code, we might help out.



 

-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/5f91c74d-12e6-499e-b7ad-6918048604dd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to