stkvtflw
stkvtflw

Reputation: 13507

How to make function wait for another?

i have a function, that call another function:

function_name(1)
function function_name (i) {
  multiply(i)
  console.log(i); // 1
}
function multiply (i) {
  i = i*2
}

When it's executing, console.log(i) return "1". I need console.log(i) to return "2". how can i make it wait till multiply() will be executed?

Upvotes: 0

Views: 225

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

There is no need to wait, those methods are synchronous so the console.log() is executing only after the multiply() is executed. The problem is you are only updating the local scoped variable i in the multiply so the locally scoped variable i in function_name will not be modified by the actions in multiply

You can return the result from multiply and use that value in the calling function like

function_name(1);

function function_name(i) {
    i = multiply(i);
    console.log(i); // 1
}

function multiply(i) {
    return i * 2;
}

Upvotes: 10

Kolja
Kolja

Reputation: 868

Right now i is never changed.

If you do the below, it should work:

function_name(1);
function function_name (i) {
  i = multiply(i);
  console.log(i); // 2
}
function multiply (i) {
  return i = i*2;
}

Upvotes: 3

Oliver
Oliver

Reputation: 1644

Try this.

function_name(1)

function function_name (i) {
  i = multiply(i); //Makes 'i' equal to the value returned
  console.log(i); // 2
}

function multiply (i) {
  return i = i * 2; // returns the value
}

Upvotes: 2

Related Questions