Correct Try…Catch Syntax Using Async/Await

前端 未结 4 1151
闹比i
闹比i 2020-11-22 05:01

I like the flatness of the new Async/Await feature available in Typescript, etc. However, I\'m not sure I like the fact that I have to declare the variable I\'m

4条回答
  •  庸人自扰
    2020-11-22 05:34

    @Bergi Answer is good, but I think it's not the best way because you have to go back to the old then() method, so i think a better way is to catch the error in the async function

    async function someAsyncFunction(){
        const createdUser = await this.User.create(userInfo);
    
        console.log(createdUser)
    }
    
    someAsyncFunction().catch(console.log);
    
    • But what if we have many await in the same function and need to catch every error?

    You may declare the to() function

    function to(promise) {
        return promise.then(data => {
            return [null, data];
        })
        .catch(err => [err]);
    }
    
    

    And then

    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();
    

    When reading this its: "Wait to this.User.create".

    Finally you can create the module "to.js" or simply use the await-to-js module.

    You can get more information about to function in this post

提交回复
热议问题