I am currently working on a project where I need to develop a service that can take CSV data, convert it into rows, and then make API requests for each row, adding the formatted results to an output string.
To explain further, my code (written in Coffeescript) looks something like this:
$s.batchFetch = ->
return unless $s.csv
$s.output = ''
for row in $s.csv.split("\n")
$s._addToOutput(row)
The $s._addToOutput()
function is responsible for making an API call with each row, formatting the response, and appending it to the output string ($s.output
). Here is a simplified version of how it works:
$s._addToOutput (row) = ->
formattedResponse = ''
$http.get("api/request/path/row-specific-whatever")
.success (res) ->
formattedResponse = $s._format(res)
.then ->
$s.output += formattedResponse
The issue at hand is that the order of the responses added to the output string seems random. It appears that the speed of the API responses varies, causing responses to be added out of order based on when they are received -- rather than following the original order of the rows
.
I believe that using Angular promise chaining could potentially solve this problem, as shown here:
$s._addToOutput(row).then ->
$s._addToOutput(secondRow).then ->
$s._addToOutput(thirdRow).then ->
...
However, since the number of incoming rows is unpredictable, I would like a more dynamic solution that allows me to perform API calls for each row sequentially.
If anyone has any suggestions on how to achieve this, I would greatly appreciate the assistance. Thank you!
Sasha
EDIT -- I attempted ryeballar's solution, but unfortunately, it did not resolve the reordering issue. I suspect there may be an error in my implementation, so if anyone notices anything amiss, please let me know:
(Please note, I had to modify the solution slightly due to making two consecutive requests for each row: one for the "venue" and another for the venue's "photo." Also, yamlify
essentially means 'format'.)