Eddy
Eddy

Reputation: 3703

Return from a Promise.all doesn't return from the wrapping function

I want to return from a function if some condition is met once Promise.all resolves. But the return statement doesn't seem to have an effect and the function execution continues.

Here's my code:

function somefunc() {

    Promise.all([match2, match3, match4, match5]).then(results => {
        console.log(results);
        if(results.indexOf(false) > -1) {
            return; // has no effect. somefunc() does NOT return. 
        }
        else {
            // ............
        };

    }).catch(err => {
      console.log(err);
    });

    // this continues to get executed even after the return staement
}

Upvotes: 0

Views: 46

Answers (2)

Luca Kiebel
Luca Kiebel

Reputation: 10096

You have to return Promise.all if you want something in it's Promise chain to be returned:

function somefunc() {

    return Promise.all([match2, match3, match4, match5]).then(results => {
        console.log(results);
        if(results.indexOf(false) > -1) {
            return; // has an effect. somefunc() will return. 
        }
        else {
            // ............
        };

    }).catch(err => {
      console.log(err);
    });

    // this will not get executed after the return staement
}

Upvotes: 2

t.niese
t.niese

Reputation: 40852

Promise.all([ is resolve asynchronous, so // this continues to get executed even after the return staement will be always be executed before the code within the then runs.

You have to either use await/async:

async function somefunc() {
  try {
    var results = await Promise.all([match2, match3, match4, match5]);

    if (results.indexOf(false) > -1) {
      return;
    } else {
      // ............
    };
  } catch (err) {
    console.log(err);
  }

  // code that is executed if return is not done
}

Or you need move the code of // this continues to get executed even after the return staement within the then, and you should return the Promise chain form your function, so that if someone calls somefunc is able to wait for the function to finish:

function somefunc() {

  return Promise.all([match2, match3, match4, match5]).then(results => {
    console.log(results);
    if (results.indexOf(false) > -1) {
      return; // has no effect. somefunc() does NOT return. 
    } else {
      // ............
    };

    // code that is executed if return is not done
  }).catch(err => {
    console.log(err);
  });
}

Upvotes: 1

Related Questions