简体   繁体   English

Node.js | 遍历数组,进行post调用并在数组中累积结果

[英]Node.js | loop over an array , make post calls and accumulate result in an array

I wish to make a call in Node.js somethine like this (im using coffeescript for node.js) 我希望以这种方式在Node.js中打电话(即在node.js中使用coffeescript)

test = [] //initially an empty array
list = []//an array with 10 json object

for li in list
  get_data url , li, (err,data) -> test.push data

my get_data method look like 我的get_data方法看起来像

get_data: (url, json_data, callback) ->
  throw "JSON obj is required" unless _.isObject(json_data) 
  post_callback = (error, response) ->
    if error
      callback(error)
    else
      callback(undefined, response)
    return
  request.post {url: url, json: json_data}, post_callback
  return

problem is I am not able to collect the result from request.post into the 'test' array I Know I am doing something wrong in the for loop but not sure what 问题是我无法从request.post收集结果到'test'数组中,我知道我在for循环中做错了什么,但不确定

You don't appear to have any way of knowing when all of the requests have returned. 您似乎无法知道何时所有请求都已返回。 You should really consider using a good async library , but here's how you can do it: 您应该真正考虑使用一个好的异步库 ,但这是您可以执行的方法:

test = [] //initially an empty array
list = []//an array with 10 json object

on_complete = ->
  //here, test should be full
  console.log test
  return

remaining = list.length
for li in list
  get_data url , li, (err,data) ->
    remaining--
    test.push data
    if remaining == 0
      on_complete()

In just looking at your code (not trying it out), the problem seems to be a matter of "when you'll get the response" rather than a matter of "if you'll get the response". 仅查看您的代码(不尝试),问题似乎是“何时获得响应”而不是“是否获得响应”。 After your for loop runs, all you have done is queue a bunch of requests. 在for循环运行之后,您要做的就是将一堆请求排队。 You need to either design it so the request for the second one doesn't occur until the first has responded OR (better) you need a way to accumulate the responses and know when all of the responses have come back (or timed out) and then use a different callback to return control to the main part of your program. 您需要设计它,以便在第一个请求响应之前,第二个请求不会发生,或者(更好),您需要一种积累响应并知道何时所有响应都返回(或超时)的方法,以及然后使用其他回调将控制权返回到程序的主要部分。

BTW, here is code for a multi-file loader that I created for ActionScript. 顺便说一句, 是我为ActionScript创建的多文件加载器的代码。 Since I/O is asynchronous in ActionScript also, it implements the accumulating approach I describe above. 由于I / O在ActionScript中也是异步的,因此它实现了我上面描述的累积方法。 It uses events rather than callbacks but it might give you some ideas on how to implement this for CoffeeScript. 它使用事件而不是回调,但是可能会为您提供一些有关如何为CoffeeScript实现此功能的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM