[英]How to convert Asynchronous to Synchronous in node js
I'm a rookie in nodejs.And now I occured a problem about Asynchronous and Synchronous in node js.我是nodejs的菜鸟。现在我在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.我已经学习并尝试了一些关于异步到同步的方法,但我没有成功。而且我必须在 readFile 中使用异步方法。
So how can I get ["a","b","a","b","a","b"]?那么我怎样才能得到 ["a","b","a","b","a","b"] 呢? Who can give me some advice?谁能给我一些建议?
Thanks a lot!非常感谢!
You cannot convert something async into sync, but you can make your rest implementation wait for the async func to complete您无法将异步转换为同步,但您可以让 rest 实现等待异步函数完成
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) {
const fs = require('fs').promises;
if (aInfo == "a") {
try {
await fs.readFile("./debug.json")
txs_arr_tmp.push("a");
} catch (error) {
console.log(error)
var obj_addr = {
"success": false,
"error_no": 1,
"error_info": "err with addrs"
}
return res_send.jsonp(obj_addr);
}
} 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);
})
If fs' promisified methods are not available如果 fs 的承诺方法不可用
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) {
let util = require('util');
const readFile = util.promisify(require('fs').readFile);
if (aInfo == "a") {
try {
await readFile("./debug.json")
txs_arr_tmp.push("a");
} catch (error) {
console.log(error)
var obj_addr = {
"success": false,
"error_no": 1,
"error_info": "err with addrs"
}
// return res_send.jsonp(obj_addr);
}
} 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);
})
Here's how I would approach writing the function.以下是我编写 function 的方法。 Since your version of Node.js doesn't have support for the fs.promises
API , you can use util.promisify()
to convert fs.readFile()
from a callback API to a promise API, then use Array.prototype.map()
to create an array of promises and await
the readFile()
calls in parallel with Promise.all()
: Since your version of Node.js doesn't have support for the fs.promises
API , you can use util.promisify()
to convert fs.readFile()
from a callback API to a promise API, then use Array.prototype.map()
创建一个 promise 数组并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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.