【发布时间】:2020-02-05 07:14:55
【问题描述】:
我有一个提交功能
const onSubmit = async (creditCardInput) => {
const { navigation } = this.props;
this.setState({ submitted: true });
let creditCardToken;
try {
creditCardToken = await getCreditCardToken(creditCardInput);
if (creditCardToken.error) {
this.setState({ submitted: false});
return;
}
} catch (e) {
this.setState({ submitted: false });
return;
}
try {
const obj = await subscribeUser(creditCardToken);
console.log('returned obj', obj);
try {
const docRef = await this.db.collection("users").doc(this.user.email).set({
id: this.user.uid,
subscriptionId: obj.customerId,
active: true
});
console.log("Document written with ID: ", docRef);
this.navigateToScreen('HomeScreen');
} catch (e) {
console.log("Error adding document: ", e);
}
} catch (error) {
console.log('catch error', error);
this.setState({ submitted: false, error: SERVER_ERROR, message: error });
}
};
这是正常工作的 - 当 this.db.collection 调用失败时,捕获被实现意味着它会注销“添加文档时出错:”,e 见下面的代码sn-p
try {
const docRef = await this.db.collection("users").doc(this.user.email).set({
id: this.user.uid,
subscriptionId: obj.customerId,
active: true
});
console.log("Document written with ID: ", docRef);
this.navigateToScreen('HomeScreen');
} catch (e) {
console.log("Error adding document: ", e);
}
但是,当我以不同的方式实现 subscribe 用户函数时(见下文),我不再使用 try catch 而是使用 .then 内部函数最终失败并且执行外部 catch 语句意味着它注销console.log('捕获错误', 错误);什么时候应该退出 console.log("Error added document:", errors); 这是为什么?它们不应该以相同的方式工作吗,这意味着上面和下面的代码 sn-p 应该以相同的方式工作 见下面的代码
await subscribeUser(creditCardToken).then((obj)=> {
this.db.collection("users").doc(this.user.email).set({
id: this.user.uid,
subscriptionId: obj.customerId,
active: true
}).then((docRef) => {
console.log("Document written with ID: ", docRef);
this.navigateToScreen('HomeScreen');
}).catch((errors) => {
console.log("Error adding document: ", errors);
});
}).catch((error) => {
console.log('catch error', error);
this.setState({ submitted: false message: error });
});
当 this.db.collections 成功解析 .then 时,只是添加了一条注释执行外部捕获而不是内部捕获
还向 this.db.collection 函数添加 return 并删除 await 对结果没有影响
【问题讨论】:
-
您是否考虑过使用最后一段代码更好地使用缩进 - 因为它看起来像一个扁平的 .then/.catch/.catch 链,但显然不是跨度>
-
试试
return this.db.collection("users") ....看看有没有效果 -
顺便说一句,像这样同时使用 async/await 和 .then/.catch 几乎不是“正确的”
-
在 SO 上缩进时遇到了问题,没有从编辑器中很好地复制 - 我会尝试返回这个,就我理解的“正确”方式而言,使用 try catch 对 async 和 await 更好,但它们应该可以工作与 promises 相同的方式,所以即使认为它可能不正确,我认为它应该仍然具有相同的功能
-
缺少的
return可能会有所不同 - 你试过了吗?
标签: javascript firebase promise async-await