node.js - NodeJS: How to use for async helper method for async method -
i'm using async
library asynchronous programming on nodejs. want make helper method (that use async method), rather put code in same place.
here sample code:
var solve = function() { async.waterfall([ // long working task. huh function (callback) { settimeout(function() { console.log('hello world!'); callback(); }, 2000); }, function (callback) { authorservice.helperasync(); }, function (callback) { settimeout(function() { console.log('bye bye!'); }, 2000); } ]); }; solve();
in other file, make async function:
var helperasync = function() { async.waterfall([ function(callback) { console.log('task 1'); callback(); }, function (callback) { console.log('task 2'); callback(); } ]); }
i want result should be:
hello world task 1 task 2 bye bye
but output
hello world task 1 task 2
. how can fix code ?
thanks :)
you need setup each file used module
, involves exporting
function you'd return, so:
solve.js
var async = require('async'); var helperasync = require('./helperasync.js'); module.exports = function solve() { async.waterfall([ function helloone(next) { settimeout(function() { console.log('hello world!'); return next(); }, 2000); }, function helpercall(next) { helperasync(params, function(){ return next(); }); }, function byebye(next) { settimeout(function() { console.log('bye bye!'); return next(); }, 2000); } ], function(result){ return result; }); };
helperasync.js
var async = require('async'); module.exports = function helperasync (params, callback) { async.waterfall([ function(next) { console.log('task 1'); return next(); }, function (next) { console.log('task 2'); return next(); } ], function(result){ return callback(result); }); };
i've renamed callback
async.waterfall
next
in order prevent confusion main callback of module.
Comments
Post a Comment