【问题标题】:how to use promise for loop in my case在我的情况下如何使用promise for循环
【发布时间】:2017-03-30 02:13:09
【问题描述】:

我没有在 for 循环中使用 Promise。我需要连续完成 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

【问题讨论】:

标签: javascript api asynchronous coffeescript promise


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-02-22
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2023-02-05
    • 2021-06-19
    • 2021-05-29
    相关资源
    最近更新 更多