Correct Try…Catch Syntax Using Async/Await

前端 未结 4 1150
闹比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:37

    I usually use the Promise's catch() function to return an object with an error property on failure.

    For example, in your case i'd do:

    const createdUser = await this.User.create(userInfo)
              .catch(error => { error }); // <--- the added catch
    
    if (Object(createdUser).error) {
        console.error(error)
    }
    

    If you don't like to keep adding the catch() calls, you can add a helper function to the Function's prototype:

    Function.prototype.withCatcher = function withCatcher() {
        const result = this.apply(this, arguments);
        if (!Object(result).catch) {
            throw `${this.name}() must return a Promise when using withCatcher()`;
        }
        return result.catch(error => ({ error }));
    };
    

    And now you'll be able to do:

    const createdUser = await this.User.create.withCatcher(userInfo);
    if (Object(createdUser).error) {
        console.error(createdUser.error);
    }
    


    EDIT 03/2020

    You can also add a default "catch to an error object" function to the Promise object like so:

    Promise.prototype.catchToObj = function catchToObj() {
        return this.catch(error => ({ error }));
    };
    

    And then use it as follows:

    const createdUser = await this.User.create(userInfo).catchToObj();
    if (createdUser && createdUser.error) {
        console.error(createdUser.error);
    }
    

提交回复
热议问题