首页 > 解决方案 > 如何检查 Node.js 中的 Async-await 是否发生错误?

问题描述

在 node.js 中开发时,我遇到了 async-await,尤其是这些示例:


function readFortunesBeforeAsyncFunctions(callback) {
   const fortunesfn = process.env.FORTUNE_FILE;
   fs.readFile(fortunesfn, 'utf8', (err, fortunedata) => {
       // errors and results land here
       // errors are handled in a very unnatural way
       if (err) {
           callback(err);
       } else {
          // Further asynchronous processing is nested here
           fortunes = fortunedata.split('\n%\n').slice(1);
           callback();
       }
   });
   // This is the natural place for results to land
   // Throwing exceptions is the natural method to report errors
}
import fs from 'fs-extra';

let fortunes;

async function readFortunes() {
    const fortunesfn = process.env.FORTUNE_FILE;
    const fortunedata = await fs.readFile(fortunesfn, 'utf8');
    fortunes = fortunedata.split('\n%\n').slice(1);
}

export default async function() {
    if (!fortunes) {
        await readFortunes();
    }
    if (!fortunes) {
        throw new Error('Could not read fortunes');
    }
    let f = fortunes[Math.floor(Math.random() * fortunes.length)];
    return f;
};

在这两种情况下,作者 ( robogeek) 都会尝试读取财富文件并显示随机财富。在回调方法中,根据常见的 javascript 编码约定,通过 提供的回调fs.read具有第err一个参数,因此我们可以通过查看通过参数提供的值来检查错误。

如果err' 的值为 null 则全部为绿色且未发生错误。

在异步方法中,如果发生任何错误,我该如何处理,尤其是在利用回调传递错误的 api 中,例如使用 mandrill api:

var mandrill = require('node-mandrill')('ThisIsMyDummyApiKey');

const sendEmail = async () => {

mandrill('/messages/send', {
    message: {
        to: [{email: 'git@jimsc.com', name: 'Jim Rubenstein'}],
        from_email: 'you@domain.com',
        subject: "Hey, what's up?",
        text: "Hello, I sent this message using mandrill."
    }
}, function(error, response)
{
    //uh oh, there was an error
    if (error) console.log( JSON.stringify(error) );

    //everything's good, lets see what mandrill said
    else console.log(response);
});

}

/**
 * How I Need to refactor my method in order to handle errors with the following piece of code?
*/
await sendEmail()


标签: javascriptnode.jsasync-await

解决方案


一个干净的解决方案是从你的异步函数中返回一个 Promise。您的代码将如下所示:

import fs from 'fs-extra';

let fortunes;

async function readFortunes() {
    const fortunesfn = process.env.FORTUNE_FILE;
    const fortunedata = await fs.readFile(fortunesfn, 'utf8');
    return new Promise((resolve, reject) => fortunedata.split('\n%\n').slice(1));
}

export default async function() {
    await readFortunes()
        .then(data => { return fortunes[Math.floor(Math.random() * fortunes.length)]; }, 
            err => throw new Error('Could not read fortunes', err)
    );

};

推荐阅读