I have a code

ids = [196658162, 244668541, 84634196, 1234567, 45367181] for id of ids id = ids[id] url = "https://api.vk.com/method/users.get?fields=photo,status&user_ids=#{id}&access_token=#{atom.config.get('vk-messenger.apiToken')}&v=5.60" reqWithPromise(url) reqWithPromise = (url) -> return new Promise((resolve, reject) -> https.get url, (@response) -> @response.on 'data', (chunk) -> @userModel = JSON.parse(chunk)['response'][0] console.log @userModel.id + ' ' + @userModel.first_name resolve() ) 

in the console I get

 1234567 Maximka dialogs-service.coffee:26 244668541 Maxim dialogs-service.coffee:26 45367181 Daniil dialogs-service.coffee:26 84634196 Igor dialogs-service.coffee:26 196658162 Nikita dialogs-service.coffee:26 

Help how to make the requests go and come consistently.

  • @PavelMayorov you know how you can solve this problem? - Andrei Shostik

1 answer 1

In order for a new operation to be carried out strictly after the old one, one must begin to do it in the continuation of the old one. To do this, the "old" promise (promise) must be saved between iterations of the cycle:

 var last = Promise.resolve(); for (var id of ids) { let url = `...`; last = last.then(() => reqWithPromise(url)); } 

(I am writing to javascript because I am not familiar with coffeescript syntax)

It can be seen that the last variable plays the role of a battery, it accumulates a chain of calls.

You can also use the reduce method to build this chain:

 ids.reduce((last, id) => last.then(() => reqWithPromise(`...`)), Promise.resolve()); 

Both methods above build a long chain of promises immediately. If this behavior does not suit you, then it is necessary to do a cycle through recursion:

 function reqWithPromiseSeq(ids) { step(0); function step(index) { if (index >= ids.length) return; var url = `...`; reqWithPromise(url).then(() => step(index+1)); } } 

And finally, you can refuse promises and use the async library instead - it seems that the function of eachSeries does exactly what you need.

  • The first option turns all 5 times the object of the user whose id is the last in the array - Andrey Shostik
  • @AndreyShostik means you wrote something wrong. - Pavel Mayorov