How to reject in async/await syntax?

后端 未结 7 1740
无人及你
无人及你 2020-11-28 17:56

How can I reject a promise that returned by an async/await function?

e.g. Originally:

         


        
相关标签:
7条回答
  • 2020-11-28 18:29

    A better way to write the async function would be by returning a pending Promise from the start and then handling both rejections and resolutions within the callback of the promise, rather than just spitting out a rejected promise on error. Example:

    async foo(id: string): Promise<A> {
        return new Promise(function(resolve, reject) {
            // execute some code here
            if (success) { // let's say this is a boolean value from line above
                return resolve(success);
            } else {
                return reject(error); // this can be anything, preferably an Error object to catch the stacktrace from this function
            }
        });
    }
    

    Then you just chain methods on the returned promise:

    async function bar () {
        try {
            var result = await foo("someID")
            // use the result here
        } catch (error) {
            // handle error here
        }
    }
    
    bar()
    

    Source - this tutorial:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

    0 讨论(0)
提交回复
热议问题