0

I have two functions function1 and function2. I want to call the function2 after the function1 is complete and want to use function1's return value as function2's parameter

when I call these functions, the function2 is executing first

var a = function1();

function2(a);

I checked this answer:

Call a function after previous function is complete

but I want to return a value from function1 and use it in function2. How can I do that?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Ansar
  • 15
  • 6
  • can u show us ur code – sayalok Oct 14 '19 at 04:59
  • 1
    is `function1` asynchronous? – Nick Parsons Oct 14 '19 at 05:01
  • @Nick. it is not asynchronous. the first function is in another page while second function is in the same page of calling – Ansar Oct 14 '19 at 05:03
  • 1
    No, `function2` will never be executing first. But maybe `function1` doesn't immediately return the result you expect. Please post their code. – Bergi Oct 14 '19 at 05:03
  • @sayalok function1() is a big function which calls many google api operations like list events from google calendar , save events, update events and it took some time to return the eventId which i want to use in my second function – Ansar Oct 14 '19 at 05:13
  • 1
    @Ansar So it actually *is* asynchronous. – Bergi Oct 14 '19 at 05:38

2 Answers2

0

You can use JavaScript CallBak like this:

var a;

function function1(callback) {
 console.log("First comeplete");
 a = "Some value";
 callback();
}
function function2(){
 console.log("Second comeplete:", a);
}


function1(function2);

Or Java Script Promise:

let promise = new Promise(function(resolve, reject) { 
  // do function1 job
  let a = "Your assign value"
  resolve(a);
});

promise.then(             

function(a) {
 // do function2 job with function1 return value;
 console.log("Second comeplete:", a);
},
function(error) { 
 console.log("Error found");
});
Imranmadbar
  • 4,681
  • 3
  • 17
  • 30
0

you can use await and async for this

  function f1() {

        return "value"
    }

    async function f2() {

        let result = await f1();
        console.log(result);
    }

    f2();
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20