'then'和'catch'相继打来电话
'then' and 'catch' called one after annother
为什么我加了回调函数,'then'和'catch'都会被调用?
function sendMail(data, callback) {
sgMail
.send(data)
.then(() => {
console.log('Email sent');
callback(true);
})
.catch((error) => {
console.error(error);
callback(false);
})
}
很抱歉,如果重复,我找不到答案。
catch()
将 运行 如果前一个 then()
中的代码抛出错误。
举个例子:
const promise = new Promise((resolve) => {
resolve({ data: true })
})
promise.then(() => {
console.log('Email sent');
throw new Error("throw an error")
})
.catch((error) => {
console.error(error);
console.log('Error was thrown in then() clause');
})
承诺解析成功,then()
执行直到抛出错误,然后 catch
是 运行 因为抛出了错误。
但是这个例子从来没有 运行s catch()
因为没有错误被抛出。
const promise = new Promise((resolve) => {
resolve({ data: true })
})
promise.then(() => {
console.log('Email sent');
})
.catch((error) => {
console.error(error);
console.log('Error was thrown in then() clause');
})
为什么我加了回调函数,'then'和'catch'都会被调用?
function sendMail(data, callback) {
sgMail
.send(data)
.then(() => {
console.log('Email sent');
callback(true);
})
.catch((error) => {
console.error(error);
callback(false);
})
}
很抱歉,如果重复,我找不到答案。
catch()
将 运行 如果前一个 then()
中的代码抛出错误。
举个例子:
const promise = new Promise((resolve) => {
resolve({ data: true })
})
promise.then(() => {
console.log('Email sent');
throw new Error("throw an error")
})
.catch((error) => {
console.error(error);
console.log('Error was thrown in then() clause');
})
承诺解析成功,then()
执行直到抛出错误,然后 catch
是 运行 因为抛出了错误。
但是这个例子从来没有 运行s catch()
因为没有错误被抛出。
const promise = new Promise((resolve) => {
resolve({ data: true })
})
promise.then(() => {
console.log('Email sent');
})
.catch((error) => {
console.error(error);
console.log('Error was thrown in then() clause');
})