从Promises转移到异步/等待如何更好地处理错误

时间:2018-04-30 16:37:06

标签: javascript promise async-await

有人可以解释为什么我能够在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 :(得分:0)

这似乎是将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();