2016-11-16 38 views
-2

我未能在for循环中使用承诺。我需要先后得到reqWithPromise方法完成如何在我的情况下使用承诺循环

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 
+1

[闭合的可能的复制范围未被捕获? - Coffeescript](http://stackoverflow.com/questions/11996218/closure-scope-not-captured-coffeescript) –

回答

0

您可以使用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