Javascript 如何在我的案例中使用promise for loop
我没有在for循环中使用承诺。我需要用承诺的方法成功完成需求Javascript 如何在我的案例中使用promise for loop,javascript,api,asynchronous,coffeescript,promise,Javascript,Api,Asynchronous,Coffeescript,Promise,我没有在for循环中使用承诺。我需要用承诺的方法成功完成需求 getUserInfoById: () -> ids = [196658162, 244668541, 84634196, 1234567, 45367181] last = Promise.resolve() for id of ids id = ids[id] url = "https://api.vk.com/method/users.get?fields=photo,status&us
getUserInfoById: () ->
ids = [196658162, 244668541, 84634196, 1234567, 45367181]
last = Promise.resolve()
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"
last = last.then(() -> reqWithPromise(url));
reqWithPromise = (url) ->
https.get url, (@response) ->
@response.on 'data', (chunk) ->
@userModel = JSON.parse(chunk)['response'][0]
console.log @userModel.id + ' ' + @userModel.first_name
我得到
5 times: 45367181 Daniil
您可以使用
reduce
并承诺按顺序处理您的通话:
getUserInfoById: () ->
ids = [196658162, 244668541, 84634196, 1234567, 45367181]
ids.reduce((memo, id)->
# Check that the previous promise is resolved
memo.then ->
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"
# Call next promise func.
reqWithPromise(url)
, Q()) #First memo value is a promise
reqWithPromise = (url) ->
# should return a promise
deferred = Q.defer()
https.get url, (@response) ->
@response.on 'data', (chunk) ->
@userModel = JSON.parse(chunk)['response'][0]
console.log @userModel.id + ' ' + @userModel.first_name
deferred.resolve(@userModel)
deferred.promise
可能重复的