javascript - 如何检查 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()
解决方案
一个干净的解决方案是从你的异步函数中返回一个 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)
);
};
推荐阅读
- java - 使用 groupBy 进行 Flux 并行串行执行
- javascript - 如何处理 setTimeout() 块内的 async/await 调用?
- python - Tkinter:如何将参数从入口传递到函数(以及退出时出现故障)
- rust - 如何启用?用铁锈代替展开的功能?
- python - Pandas - Vlookup - 搜索列中的重复值
- c++ - C/C++ 远程编译,带有 ELF 的本地调试会话(嵌入式,Cortex-M)
- javascript - 如何禁用单行的流(JS)类型检查
- javafx - 如何引用 TestFX 中的顶级节点?
- python - 如何在 Python 中查找列表行和列的索引
- python - 按行循环,然后使用熊猫按列循环