我是nodejs的菜鸟,现在我在node js中出现了关于异步和同步的问题。
这是我的代码:
var time_begin = Date.now();
console.log("begin time:" + time_begin);
arr_a = ['a', 'b', 'a', 'b', 'a', 'b']
async function iterTrans (arr_a) {
var txs_arr_tmp = [];
for(let aInfo of arr_a) {
var fs = require('fs');
if (aInfo == "a") {
fs.readFile("./debug.json", function (error_file, data_file) {
if (error_file) {
console.log(error_file)
} else {
txs_arr_tmp.push("a");
}
});
} else {
txs_arr_tmp.push("b");
}
}
return txs_arr_tmp;
}
iterTrans(arr_a).then((txs_arr_tmp) => {
var content_str = JSON.stringify(txs_arr_tmp);
console.log(content_str);
})
我希望控制台可以打印:
["a","b","a","b","a","b"]
但是我实际上得到了:
["b","b","b"]
我已经学习并尝试了一些有关从异步到同步的方法,但没有成功,而且我必须在readFile中使用异步方法。
那么如何获得[“ a”,“ b”,“ a”,“ b”,“ a”,“ b”]?谁能给我一些建议?
非常感谢!
这是我编写函数的方法。由于您的Node.js的版本不具备的支持fs.promises
API,你可以使用util.promisify()
转换fs.readFile()
从回调API的承诺API,然后使用Array.prototype.map()
创建承诺的数组,并await
在readFile()
与并行调用Promise.all()
:
const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
const time_begin = Date.now();
console.log("begin time:" + time_begin);
const arr_a = ['a', 'b', 'a', 'b', 'a', 'b'];
async function iterTrans (arr_a) {
// array map allows parallel asynchronicity
const txs_arr_tmp_promises = arr_a.map(async aInfo => {
// use early return (to avoid nesting large blocks inside if statements)
if (aInfo !== 'a') return 'b';
// let await throw here if file error occurs
const data_file = await readFile('./debug.json');
return 'a';
});
return Promise.all(txs_arr_tmp_promises);
}
iterTrans(arr_a).then(txs_arr_tmp => {
const content_str = JSON.stringify(txs_arr_tmp);
console.log(content_str);
}).catch(error => {
// handle errors here
console.log(error);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句