【问题标题】:How to handle errors with Async and Await [Node.js]如何使用 Async 和 Await [Node.js] 处理错误
【发布时间】:2021-12-31 20:46:01
【问题描述】:

我已经用 bluebird promises 编写了一个函数,我想用 async 和 await 重写它。当我进行更改时,我发现之前使用 promise 时,reject 语句总是将控制权转移到调用的函数 catch 块,尽管如果 catch 块已经存在于我们拒绝的文件中。如何使用 async 和 await 正确处理这种情况? (在代码中添加了 cmets 来解释问题)

承诺:

const callingFunc = (req, res) => {

    return new Promise((resolve, reject) => {
        // execute request which returns promise
        functionCall()
            .then((response) => {
                let error;

                try {
                    xml2js(response.body, { explicitArray: false }, (err, result) => {
                        if (err) {
                            return reject(err); /* throws the correct error to catch block of the file from where callingFunc is called*/ 
                        }

                        if (!_.isEmpty(result.Response.errorCode)) {
                            return reject(result.Response); /* throws the correct error to the catch block of the file from where callingFunc is called*/ 
                        }

                        return resolve(result);
                    });
                } catch (e) {
                    error = new Error('xml2js conversion error');
                    reject(error);
                }
            })
            .catch((error) => {
                const Error = new Error('Internal Server Error');
                reject(Error);
            });
    });
};

使用异步和等待:

const callingFunc = (req, res) => {

    try {
        const response = await functionCall();
        let error;

        try {
            xml2js(response.body, { explicitArray: false }, (err, result) => {
                if (err) {
                    throw (err); /* throws the error to the below catch block and returning xml2js conversion error and changing behaviour*/ 
                }

                if (!_.isEmpty(result.Response.errorCode)) {
                    throw result.Response; /* throws the error to the below catch block and returning xml2js conversion error and changing behaviour*/
                }

                return result;
            });
        } catch (e) {
            error = new Error('xml2js conversion error');
            throw error;
        }
    } catch(error) {
        const Error = new Error('Internal Server Error');
        throw Error;
    }
}; 

【问题讨论】:

    标签: javascript node.js async-await promise


    【解决方案1】:

    如果functionCall返回一个promise,那么这段代码是不合适的......

    return new Promise((resolve, reject) => {
        // execute request which returns promise
        functionCall()
            .then((response) => {
    

    如果xml2js 是使用回调异步的,那么将其包装在一个promise 中是合适的...

    // return a promise that resolves with the result of xml2js
    async function xml2js_promise(body) {
      return new Promise((resolve, reject) => {
        xml2js(body, { explicitArray: false }, (err, result) => {
          if (err) reject(err);
          else if (!_.isEmpty(result.Response.errorCode)) reject(result.Response);
          else resolve(result);
        });
      });
    }
    

    现在我们可以等待这些了。没有必要嵌套 try 的。 (而且你只需要在你想要做某事的时候尝试一下)。

    async callingFunction = (req, res) => {
        try {
          const response = await functionCall();
        } catch (error) {
          // do something with this error
        }
        try {
          const result = await xml2js_promise(response.body)
        } catch(error) {
          // do something with this error
        }
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-03
      • 1970-01-01
      • 2018-04-13
      • 2021-10-30
      • 2018-03-11
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多