有人可以解释为什么我能够在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();
答案 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();