简体   繁体   中英

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

Whilst developing in node.js I came across with async-await especially with these examples:


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

In both cases the autor ( robogeek ) tries to read a fortune file and show random fortunes. In the callback approach, the callback provided via the fs.read has the err as first argument, per common javascript coding convention, so we can check the error by peeking the value offered via the argument.

If err 's value is null then all green and no error has occured.

On the async approach how I can handle if any error occurs, especially in api's that utilize callbacks to pass around the error, for example using the 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()


When you have an async function, you can call your function like this:

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

As you can see by encapsulating your asynchronous function call in a try/catch block you can gain access to any errors that occur while executing and awaiting a response.

By the way your gists and stuff are basically copied twice.

A clean solution is to return a Promise from your async function. Your code will look like this:

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)
    );

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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