【发布时间】:2018-10-17 19:06:52
【问题描述】:
我正在学习 Javascript Promise 和 async/await。下面的示例代码异步读取并解析 node.js 中的 JSON 文件(我的 node.js 版本是 v10.0.0)。
在示例代码中,ChainReadJson 函数和 AwaitReadJson 函数做同样的事情,读取和解析 JSON 文件。区别在于ChainReadJson函数使用promise链,而AwaitReadJson函数使用async/await。
const FS = require("fs");
function ReadFile(fileName) {
return new Promise((Resolve, Reject) => {
FS.readFile(fileName, 'utf8', (error, result) => {
if (error)
Reject(error);
else
Resolve(result);
});
});
}
// function using promise chain
function ChainReadJson(fileName, CallBack) {
ReadFile(fileName)
.then(
res => JSON.parse(res),
err => {
Message(-1, err.message);
}
)
.then(
res => {
if (res !== undefined)
CallBack(fileName, res);
},
err => {
Message(-2, err.message);
}
);
}
// function using async/await
async function AwaitReadJson(fileName, CallBack) {
let res, json;
try {
res = await ReadFile(fileName);
}
catch (err) {
Message(-1, err.message);
return;
}
try {
json = JSON.parse(res);
}
catch (err) {
Message(-2, err.message);
return;
}
CallBack(fileName, json);
}
ChainReadJson('test.json', PrintJSON);
AwaitReadJson('test.json', PrintJSON);
// common functions
function PrintJSON(fileName, json) {
console.log(`JSON[${fileName}]:`, json);
}
function Message(n, str) {
console.log(`[${n}]`, str);
}
在使用 Promise 链编写 ChainReadJson 函数的代码时,我很难控制执行结果和错误。但是,当使用 async/await 编写 AwaitReadJson 函数的代码时,这些困难大部分都消失了。
我是否正确理解异步/等待的好处?与 Promise 链相比,async/await 的缺点是什么?
(示例代码是the code in this answer的修改版本。原始代码仅使用promise链,编写是为了准确知道错误发生在链中的哪个位置以及错误是什么)
【问题讨论】:
-
你对 Promise 链和 async/await 都很了解。 . .其余的是本网站不擅长的意见。忽略我的拙见,async/await 并没有任何缺点,除了它不受任何地方的支持。
-
您在使用 Promise 链时遇到了哪些错误?你是如何使用 ChainedPromiseJSON 的? 2个代码不一样,在promise链中,如果
JSON.parse的返回不是undefined,你只执行回调,而在你的等待情况下,你总是执行回调。 -
@generalhenry:感谢您的意见。
-
@cowbert :示例代码工作正常。如果您阅读this answer,您可以更轻松地理解示例代码。
-
你为什么要创建 2 个单独的问题。无论如何,如果上一步(第一个
then导致错误,那么它会在第二个then中触发错误回调)。检查res !== undefined只会在JSON.parse返回 undefined 时执行,这永远不会发生,它会抛出一个 SyntaxError。
标签: javascript node.js async-await es6-promise