Reputation: 333
Every example I see for async.js looks something like this:
var async = require(“async”);
async.series([
function(callback) {
setTimeout(function() {
console.log(“Task 1”);
callback(null, 1);
}, 300);
},
function(callback) {
setTimeout(function() {
console.log(“Task 2”);
callback(null, 2);
}, 200);
},
function(callback) {
setTimeout(function() {
console.log(“Task 3“);
callback(null, 3);
}, 100);
}
], function(error, results) {
console.log(results);
});
At the end they always just console.log the results. But, how do you actually return the results. Every time I try it just comes back as undefined.
I need something like this:
var async = require('async');
var handler = function()
{
async.series([
function(callback) {
setTimeout(function() {
console.log('Task 1');
callback(null, 1);
}, 300);
},
function(callback) {
setTimeout(function() {
console.log('Task 2');
callback(null, 2);
}, 200);
},
function(callback) {
setTimeout(function() {
console.log('Task 3');
callback(null, 3);
}, 100);
}
], function(error, results) {
return results;
});
}
var result = handler();
console.log(result);
But this doesn't work, the result is always undefined.
Ultimately I need to put this up on AWS Lambda and return the results with their context.succeed(results) call. But, I can never get the results. I'm obviously not understanding something about this process, if someone could help it would be much appreciated, thanks!
Upvotes: 2
Views: 1444
Reputation: 1110
try this for async series module
Details: function (req, res) {
async.series([
function functionOne(callback) {
setTimeout(function(err, response) {
console.log('Task 1');
callback(null, 1);
if (err) {
return callback(err);
}
}, 300);
},
function functionTwo(callback) {
setTimeout(function(err, response) {
console.log('Task 2');
callback(null, 2);
if (err) {
return callback(err);
}
}, 200);
},
function functionThree(callback) {
setTimeout(function(err, response) {
console.log('Task 3');
callback(null, 3);
if (err) {
return callback(err);
}
}, 200);
}
], function (err,res) {
if (err) {
return res.badRequest(err);
}
if (res) {
return response;
}
});
}
Upvotes: 0
Reputation:
You can't return result from asynchronous call. What you can do is pass the callback function and when result is available, call that callback function with result as a parameter.
var async = require('async');
var handler = function(cb)
{
async.series([
function(callback) {
setTimeout(function() {
console.log('Task 1');
callback(null, 1);
}, 300);
},
function(callback) {
setTimeout(function() {
console.log('Task 2');
callback(null, 2);
}, 200);
},
function(callback) {
setTimeout(function() {
console.log('Task 3');
callback(null, 3);
}, 100);
}
], function(error, results) {
cb(error, results)
});
}
handler(function(err, results) {
if(!err) {
console.log(results);
}
})
Upvotes: 6