![](/img/trans.png)
[英]Node JS Fetching JSON from url is executing AFTER the rest of the code
[英]Code after pipe is not executing in node js readstream
我有如下的 JSONcustomers.json
{
"customers":[
{ "name": "customer1"},
{ "name": "customer2"},
{ "name": "customer3"}
]
}
var fs = require('fs'),
JSONStream = require('JSONStream'),
es = require('event-stream');
async function run(){
var getStream = function () {
var jsonData = 'customers.json',
stream = fs.createReadStream(jsonData, { encoding: 'utf8' }),
parser = JSONStream.parse('customers.*');
return stream.pipe(parser);
};
var arr = [];
getStream()
.on('data', function (chunk) {
arr.push(chunk);
})
.on('end', function () {
console.log('All the data in the file has been read' + arr.length);
})
.on('close', function (err) {
console.log('Stream has been Closed');
});
console.log('end run()');
}
async function main(){
run().then(function(){
console.log('In then');
}).catch(function(){
console.log('In catch');
})
}
main();
在输出中为什么“In then”在“end”,“close”之前打印。 事件。
如何在“结束”、“关闭”事件之后获得“In then”或“In Catch”。
我如何以同步方式执行 run() 方法。
异步运行函数时,不一定会按顺序调用console
。 如果它是异步的,你不应该依赖于按顺序完成的任何事情。
如果你想让run()
同步,它实际上比你现在做的要简单得多,因为你根本不需要使用流。 您可以调用fs.readFileSync
从本地 json 文件加载数据。 本文解释了一些差异。
var fs = require('fs');
function run() {
const rawData = fs.readFileSync("customers.json"); // Buffer
const jsonData = JSON.parse(rawData); // object
jsonData.customers.forEach( o => console.log(o.name) );
}
function main() {
run();
console.log("done");
}
main();
控制台输出:
customer1
customer2
customer3
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.