async whilst not running fn - javascript

I want to use async.whilst function and probably missing something badly when I'm getting just the first console.log on the output.
// app.js file
var async = require('async');
var count = 0;
async.whilst(
function () {
console.log('first')
return count < 5;
},
function (callback) {
count++;
console.log('second')
callback()
},
function (err) {
console.log('third')
}
);
// run the script
$ node app.js
first
$

Have a look at the documentation: you need a callback also for the first function
var async = require('async');
var count = 0;
async.whilst(
function (callback) {
console.log('first')
return callback(null, count < 5);
},
function (callback) {
count++;
console.log('second')
callback()
},
function (err) {
console.log('third')
}
);

You should use a callback inside your first function, async make calls to subsequent function when the callback gets invoked. your code should be
async.whilst(
function (cb) {
console.log('first')
cb(null,count < 5);
},
function (callback) {
count++;
console.log('second')
callback()
},
function (err) {
console.log('third')
}
);

Related

create dynamic number callback function

i have problem to create deep number of callback function in javascript dynamically. For example i have function like this.
function process(value, callback) {
console.log('process ' + value)
callback()
}
function complete() {
console.log('complete')
}
function running(count){
// number process function is two
if (count==2) {
process('number one', function () {
process('number two', function () {
complete() => // last callback is closed by complete function
})
})
}
// number process function is three
if (count==3) {
process('number one', function () {
process('number two', function () {
process('number three', function () {
complete() => // last callback is closed by complete function
})
})
})
}
}
running(3);
Output :
process number one
process number two
process number three
completed
i want to create number callback is dynamic and closed by complete function, not using if/switch command, how to do that? thank you
You could use recursion and that will exit and run complete when the count param is zero otherwise it will call process function.
function process(value, callback) {
console.log('process ' + value)
callback()
}
function complete() {
console.log('complete')
}
const p = ['three', 'two', 'one']
function running(count) {
if (count) {
process(`number ${p[count - 1]}`, () => {
running(count - 1)
})
} else {
complete()
}
}
running(3);
You can do without using callback in this case:
var processNames = ['one', 'two', 'three'];
function process(value) {
console.log('process ' + value);
}
function complete() {
console.log('complete');
}
function running(count){
for (var index = 0; index < count; index++) {
var name = 'number ' + processNames[index];
process(name);
}
complete();
}
running(3);
You could use promises for this.
I create the three promises using a for loop and put them in an array. The resolve functions write the index to the console. Use Promise.all to execute them in order and use finally to write completed.
With the promise we don't need to provide a callback function.
function process(value) {
console.log('process ' + value)
}
function complete() {
console.log('complete')
}
const textInt = ['one', 'two', 'three']
function running(count){
const promiseArray = [];
for (let i = 0; i < count; i++)
{
promiseArray[new Promise(function(){
process(textInt[i], function(){});
})];
}
Promise.all(promiseArray).finally(complete)
}
running(3);

Node.js function parameter inject into function

I'm tring to create new function like below
function NVConvertToFV (array, func) {
var funcA = [];
for(var i=0; i<array.length; i++) {
var valueF = function (callback) {
func(array[i], callback);
}
funcA[i] = valueF;
}
return funcA;
}
But, 'func(array[i], callback);' recognized as just a string.
ex.
var funcA = [];
var msg = ['hello ', 'it ', 'is ', 'impossible!'];
function alert (para, callback) {
console.log(para);
callback(null);
}
funcA = NVConvertToFV(msg, alert);
console.log(String(funcA));
results:
function (callback) {func(array[i], callback);},
function (callback) {func(array[i], callback);},
function (callback) {func(array[i], callback);},
function (callback) {func(array[i], callback);},
Is there any possible way 'func' and 'array[i]' recognized as function and array? like,
function (callback) {alert('hello', callback);},
function (callback) {alert('it', callback);},
function (callback) {alert('is', callback);},
function (callback) {alert('impossible', callback);},
if someone help me that would be really gladful.
In NVConvertToFV() use array.forEach() instead of a normal for-loop in order to correctly capture the current value in the array so that the inner inline callback holds the correct reference. For example:
function NVConvertToFV(array, func) {
var funcA = new Array(array.length);
array.forEach(function(val, i) {
funcA[i] = function(callback) {
func(val, callback);
};
});
return funcA;
}

Use async series and parallel with exported function in node.js

I'm trying to get my code to run using the async module. However, when the async.series runs, it only executes the third() function then stops. I understand that the first argument of async.series takes an array of tasks that requires a callback. However, I'm unsure as to how I'm supposed to do a callback on a function that I've exported from another file as in the functions first() and second(). Any help?
process.js:
var process = require('child_process');
function executeProcess() {
process.exec(...);
}
exports.Process = function() {
executeProcess();
}
app.js
var process = require('./process.js');
function first() {
process.Process();
}
function second() {
process.Process();
}
function third() {
console.log('third');
}
function parallel() {
async.parallel([first, second], function() {
console.log('first and second in parallel');
});
}
async.series([third, parallel], function() {
console.log('third then parallel');
});
You should use callback functions. I think your process.js is ok so I have not changed it. But I made some minor changes in the app.js. Just added there callback functions:
var process = require('./process.js');
var async = require("async");
function first(callback) {
console.log('FIRST');
process.Process();
callback();
}
function second(callback) {
console.log('SECOND');
process.Process();
callback();
}
function third(callback) {
console.log('third');
callback();
}
function parallel() {
async.parallel([first, second], function(callback) {
console.log('first and second in parallel');
});
}
async.series([third, parallel], function() {
console.log('third then parallel');
});
This should work. Here is an very good blogpost about async library:
Node.js async in practice: When to use what?

Java script modify function at run time

enter code hereI have the following code
function a(){alert("a");}
I want to create a function b as
function b(){alert("a"); alert("b");}
My approach is something like
var b = a + alert("b");
This is of course not working. But I am wondering if there is some kind of library supporting this.
Edit: Maybe I need to describe my scenario so that its more clear what I want to achieve.
I am using async.js library to handler multiple async calls. My code looks like
var values = {};
...
function all() {
var allDfd = $.Deferred();
async.parallel(
[function (callback) {
remoteCall(function (result) {
values.v1 = result;
callback(null, 'one');
});
},
function (callback) {
remoteCall(function (result) {
values.v2 = result;
callback(null, "two");
});
},
function (callback) {
remoteCall(function (result) {
values.v3 = result;
callback(null, "three");
});
}], function (err, results) {
allDfd.resolve();
});
return allDfd.promise();
}
Clearly there are a lot of repetitive code that bothers me. So my idea is to create a function asyncCall to perform the boilerplate tasks. The idea is
var values = {};
...
function all() {
var allDfd = $.Deferred();
function getAsyncCall (func, innerCallback, callback) {
return function asyncCall(func, innnerCallback, callback){
func(innerCallback + callback(null)); // combine innerCallBack and callback code
}
}
async.parallel(
[getAsyncCall(remoteCall, function(result){values.v1=result;},callback),
getAsyncCall(remoteCall, function(result){values.v2=result;},callback),
getAsyncCall(remoteCall, function(result){values.v3=result;},callback),
], function (err, results) {
allDfd.resolve();
});
return allDfd.promise();
}
The line with the comment is what I am pondering. I am trying to create a new function that combines inner and outer callbacks.
You can do
var b = function() { a(); alert('b'); }
You could write:
var a=function(){alert("a");}
var b=function(){a(); alert("b");}
And to go a little further, you can even write a whole function composition function:
function compose( functions ) {
return function(){
for(var i=0; i!=functions.length; ++i) {
functions[i]();
}
};
}
var c=compose( [a, function(){ alert("b"); }] );
(See it at work at http://jsfiddle.net/xtofl/Pdrge/)

Passing arrays of functions to async parallel

I have to pass an array of functions to the async.js module for node.js.
The normal way from the docs would be:
async.parallel([
function(callback){
setTimeout(function(){
callback(null, 'one');
}, 200);
},
function(callback){
setTimeout(function(){
callback(null, 'two');
}, 100);
},
],
// optional callback
function(err, results){
});
I tried like this:
for(var i = 0; i < jsonData.length; i++)
{
...
o.url = serviceurl;
o.title = jsonData[i];
var ff = function(callback){
obj.loadService(o.title,o.url,callback);
}
callItems.push(ff(function(){return true;}));
}
async.parallel(
callItems,
// optional callback
function(err, results){
console.log('all calls called without any errors');
}
);
That runs through but the main callback isn't called. And so I can't say if all parallel calls are done.
What am I missing here?
It looks like the closures are improperly formed in the for loop. Try an external function that returns the value you're currently assigning to ff. Example:
for(var i = 0; i < jsonData.length; i++)
{
...
o.url = serviceurl;
o.title = jsonData[i];
var ff = makeCallbackFunc(obj, o.title, o.url);
callItems.push(ff(function () {return true;}));
}
function makeCallbackFunc(obj, title, url) {
return function (callback) {
obj.loadService(title, url, callback);
};
}
I'm a bit confused by what you are adding to callitems - namely the result of calling ff with the function parameter - it won't be a callback, it will execute right away.

Categories