Carpetfizz Carpetfizz - 4 months ago 28
Node.js Question

async.waterfall not working as expected

I'm using

async.waterfall
for the first time and I'm running into some trouble.

Here are the the two functions I'm trying to call:

function generateImageURL(data, callback){
// ... xhr stuff
xhr.onload = function () {
callback(data, JSON.parse(xhr.responseText).data.link);
}
// ... more xhr stuff
xhr.send(fd);
}


and

function generateCoordinates(data, url, callback){
console.log("CALLED"); // never gets called
navigator.geolocation.getCurrentPosition(function(p){
data.image_url = url;
data.coordinates = [p.coordinates.longitude, p.coordinates.latitude];
callback(data);
});
}


and my waterfall function looks like this:

async.waterfall([
generateImageURL.bind(this, data),
generateCoordinates
], function(err, result){

});


I want to pass in
data
from the outer scope into
generateImageURL
and then pass that data on towards
generateCoordinates
along with the
url
. The
callback
from
generateCoordinates
should call the anonymous function.

My issue is that
generateCoordinates
is never being called. Even though I call it within
generateImageURL
.

Answer

From the docs:

Each function is passed a callback(err, result1, result2, ...) it must call on completion. The first argument is an error (which can be null) and any further arguments will be passed as arguments in order to the next task.

and

If any of the tasks pass an error to their own callback, the next function is not executed.

Your callback is callback(data, JSON.parse(xhr.responseText).data.link);, you pass data as the err argument, therefore it's interpreted as an error and your next function is not called. You should see it if you console.log(err) in your final callback.

Call your callback as callback(null, data, JSON.parse(xhr.responseText).data.link);

Comments