Переход от обещаний к асинхронному / ждать, как лучше обрабатывать ошибки - PullRequest
0 голосов
/ 30 апреля 2018

Может кто-нибудь объяснить, почему я могу отлавливать ошибки в функции async, но если я использую ее в секунду async, ошибки функции не обнаруживаются?

const axios = function axios(text) {
  return new Promise((resolve, reject) => {
      reject(new Error(`Error from ${text}`));
  });
}

const firstPromise = async function firstPromise() {
  try {
    return await axios('first Promise');
  } catch(e) {
    console.log(e); // Error from first promise, as expected
  }
};

const secondPromise = function firstPromise() {
  return axios('second Promise')
      .then(res => resolve(res))
      .catch((e) => {
        console.log(e); // Error from second promise, as expected
      });
};

async function lastPromise() {
  try {
    console.log(await firstPromise());  // undefined, why not caught ?
    console.log(await secondPromise());
  } catch(e) {
    console.log(e); // error from second promise, as expected
  }
};

lastPromise();

1 Ответ

0 голосов
/ 01 мая 2018

Похоже, это правильное решение для сброса ошибок в try/catch в async/await и простого подхода Promise.

const axios = function axios(text) {
  return new Promise((resolve, reject) => {
      // resolve(text); // all good
      // if (text === 'first Promise') resolve(text); // first good
      reject(new Error(`Error from ${text}`)); // both rejected
  });
}

const firstPromise = async function firstPromise() {
  try {
    return await axios('first Promise');
  } catch(e) {
    throw e;
  }
};

const secondPromise = function firstPromise() {
  return axios('second Promise').catch(e => { 
    throw e;
  });
};

async function allPromises() {
  Promise.all([firstPromise(), secondPromise()])
    .then((res) => {
      const [a, b] = res;
      console.log(a, b);
    })
    .catch(e => {
      console.log(e);
    });
};    

allPromises(); 
...