正确尝试…使用异步/等待捕获语法我喜欢新的平整度Async/Await但是,我不确定我是否喜欢这样的事实:我必须声明我的变量await在某物的外面try...catch块以便以后使用。就像这样:let createdUsertry {
createdUser = await this.User.create(userInfo)} catch (error) {
console.error(error)}console.log(createdUser)// business// logic// goes// here如果我错了,请纠正我,但这似乎是最好的做法不将多行业务逻辑放置在try所以我只能选择宣布createdUser在块之外,在块中分配它,然后在之后使用它。这种情况下的最佳实践是什么?
3 回答
智慧大石
TA贡献1946条经验 获得超3个赞
const createdUser = await this.User.create(userInfo).catch( error => {// handle error})
皈依舞
TA贡献1851条经验 获得超3个赞
async function someAsyncFunction(){
const createdUser = await this.User.create(userInfo);
console.log(createdUser)}someAsyncFunction().catch(console.log);但如果我们有很多 await在相同的函数中需要捕获每一个错误?
to()
function to(promise) {
return promise.then(data => {
return [null, data];
})
.catch(err => [err]);}async function someAsyncFunction(){
let err, createdUser, anotherUser;
[err, createdUser] = await to(this.User.create(userInfo));
if (err) console.log(`Error is ${err}`);
else console.log(`createdUser is ${createdUser}`);
[err, anotherUser] = await to(this.User.create(anotherUserInfo));
if (err) console.log(`Error is ${err}`);
else console.log(`anotherUser is ${anotherUser}`);}someAsyncFunction();
当阅读它时:“等待此.User.create”。
to
添加回答
举报
0/150
提交
取消
