Возврат из Promise.all не возвращается из функции обтекания - PullRequest
0 голосов
/ 29 августа 2018

Я хочу вернуться из функции, если какое-то условие будет выполнено после разрешения Promise.all. Но оператор return, похоже, не дает эффекта, и выполнение функции продолжается.

Вот мой код:

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
}

Ответы [ 2 ]

0 голосов
/ 29 августа 2018

Promise.all([ является разрешением асинхронным, поэтому // this continues to get executed even after the return staement всегда будет выполняться перед выполнением кода в then.

Вы должны использовать 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
}

Или вам нужно переместить код // this continues to get executed even after the return staement в то время, и вы должны return цепочку Promise сформировать вашу функцию, чтобы, если кто-то вызывает somefunc, мог дождаться завершения функции:

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);
  });
}
0 голосов
/ 29 августа 2018

Вы должны вернуть Promise.all, если хотите, чтобы что-то в цепочке обещаний было возвращено:

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
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...