I'm a rookie in nodejs.And now I occured a problem about Asynchronous and Synchronous in node js.
Here is my code:
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);
})
I hode that the console will print:
["a","b","a","b","a","b"]
But I actually got:
["b","b","b"]
I've learned and tried some methods about Asynchronous to Synchronous, but I didn't succeed.And I must use Asynchronous method in readFile.
So how can I get ["a","b","a","b","a","b"]? Who can give me some advice?
Thanks a lot!