2

I tried to simplify my code, in essence I have this:

    function thirdPartyAPIMethod() { // Dummy method returning promise
       return Promise.resolve();
    }

    function func1() {
        console.log("func1 start");
        return thirdPartyAPIMethod().then(() => {
            console.log("func1 end");
            // ...
            resolve();
        });
    }
    
    function func2() {
        console.log("func2 start");
        // ...
        console.log("func2 end");
    }
    
    func1().then(func2());

I want to run func1 and when it completes then run func2. So I was expecting the output would be this:

func1 start
func1 end
func2 start
func2 end

But instead it prints this:

func1 start
func2 start
func2 end
func1 end

Can someone help me to do this?

Caner
  • 57,267
  • 35
  • 174
  • 180

3 Answers3

2

Modify your func1 to invoke resolve after thirdPartyAPIMethod's promise has been resolved

function thirdPartyAPIMethod() //dummy method returning promise
{
   return Promise.resolve();
}


function func1() {
    return new Promise((resolve, reject) => {
        console.log("func1 start");
        thirdPartyAPIMethod().then( () => {
           console.log("func1 end");
           resolve(); //invoke resolve here so that func1() is chained with func2 
        });
    });
}

function func2() {
    console.log("func2 start");
    console.log("func2 end");
}

func1().then( () => func2()); // then has function callback handler instead of return value of func2
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

In the call to then of the first promise, you're not passing a reference to func2, but calling it:

func1().then(func2()).catch(...);

Change it to:

func1().then(func2).catch(...);

If you want to pass parameters:

func1().then(() => func2(...)).catch(...);

Or, using the pre-ES6 syntax:

funct1().then(function() { return func2(...); }).catch(...);

Besides, when you define the promise you're not calling resolve and reject, so theoretically (except if you haven't posted all your code) that promise never completes:

function func1(...) {
    return new Promise((resolve, reject) => {
        console.log("func1 start");
        thirdPartyAPIMethod().then({
            console.log("func1 end");
            resolve(''); // resolve the promise with whichever value you want
        })
    });
}
Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
0
func1(...).then(func2(...)).catch(...);

in above code func2() is executing before passing as input.

Correct way would be

func1(...).then(func2).catch(...);

P.s the following code is equivalent to what you want to achieve.

thirdPartyAPIMethod().then(func2).catch(...)
Waqas Noor
  • 911
  • 6
  • 12