繁体   English   中英

如何检查Node.js中的Async-await是否发生错误?

[英]How I can check if an error occurs with Async-await in Node.js?

在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;
};

在这两种情况下, robogeekrobogeek )都会尝试读取财富文件并显示随机财富。 在回调方法中,根据常见的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()


当您具有异步函数时,可以这样调用函数:

async ()=>{ try { await someAsynchronousFunction() } catch (err) { console.log(err) }

如您所见,通过将异步函数调用封装在try / catch块中,您可以访问执行和等待响应时发生的任何错误。

顺便说一下,您的要点和内容基本上被复制了两次。

一个干净的解决方案是从异步函数中返回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)
    );

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM