1

Let's say I have a table that contains names and I want to use all of that names in a function. e.g var names = ['joe','sam', 'nick']; Lets say I have the following function:

function doSomething (string1, NAME, string2, callback){
   ....
   console.log(string1," ",NAME," ",string2);
   ...
   callback(null,"ok");
}

Assuming it is asynchronous, I will be using the async.each function. Moreover, I want to pass the variables in the function, using bind like this :

async.each(names,doSomething.bind(this, "example1", "example2",function(err){
   console.log(err);
});

I get the following msgs :

example1 example2 joe 
example1 example2 nick
example1 example2 sam

What I want is to bind the strings in the 1st and 3rd position and assign the name to the second. Can this be done? And how? Am I missing something in the fundamentals of JavaScript here?

2 Answers 2

5

What I want is to bind the strings in the 1st and 3rd position and assign the name to the second. Can this be done?

Not with .bind. It only allows you to bind the first n parameters, but not some of the first n.

You can simply use another function though:

async.each(names, function(name, cb) {
    doSomething("example1", name, "example2", cb);
});

and pass the arguments in any order you like.

Sign up to request clarification or add additional context in comments.

Comments

0

It may be not the prettiest solution, but you can wrap the doSomething-function and reorder the arguments:

function doSomethingReordered(string1, string2, name, cb) {
    doSomething.bind(this)(string1, name, string2, cb);
}
async.each(names,doSomethingReordered.bind(this, "example1", "example2",function(err){
   console.log(err);
});

1 Comment

doSomething.bind(this)(string1, name, string2, cb); is better be written as doSomething.call(this, string1, name, string2, cb);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.