问题描述
我有使用fs.readfile同步的问题,他们没有在第一时间inicializing,如果我再次尝试请求,然后我有结果。我知道我可以使用的承诺,我找到一些与Kriskowal Q有用。
我尝试过,但没有成功。我didn't非常理解如何实现它。如果有人能够帮助这一点,我会感激不尽。
code:
使用严格 变种Q =要求('Q');
变种FS =要求(FS);
变种arrayZipBand = [];
VAR jsonZip code = [];
VAR arrayParsedZip codeBR = []; exports.parse =功能(选){如果(opts.zipBand.constructor!=阵列){
opts.zipBand = [opts.zipBand];
}
如果(opts.location.constructor!=阵列){
opts.location = [opts.location];
}如果(opts.config === 0){
opts.zipBand.forEach(功能(文件){
fs.readFile(文件,'UTF8',函数(ERR,logData){
如果(ERR)抛出走错了路。
让文字= logData.toString();
德codeURIComponent(文本); 让线= text.split('\\ n'); lines.forEach(功能(线){
让部分= line.split('@'); 如果(部分[1]!=未定义){
让obJson = {
LOC_NU:零件[0]
LOC_CEP_INI:部分[1],
LOC_CEP_FIM:配件[2] }
arrayZipBand.push(obJson);
} });
});});opts.location.forEach(功能(文件){
fs.readFile(文件,'UTF8',函数(ERR,logData){
如果(ERR)抛出走错了路。 让文字= logData.toString();
德codeURIComponent(文本); 让线= text.split('\\ n'); lines.forEach(功能(线){
让部分= line.split('@'); 如果(部分[1]!=未定义){
对于(让我= 0; I< arrayZipBand.length;我++){
如果(部件[0] == arrayZipBand [I] .LOC_NU){
jsonZip code.push(arrayZipBand [I]);
}
}
如果(jsonZip code ===未定义){
扔是不可能找到邮编code的ID+部分[0];
} 对于(让我= 0; I< jsonZip code.length;我++){
让obJson = {
LOC_NU:零件[0]
UFE_SG:部分[1],
LOC_NO:配件[2]
MUN_NU:配件[8]
LOC_CEP_INI:jsonZip code [I] .LOC_CEP_INI,
LOC_CEP_FIM:jsonZip code [I] .LOC_CEP_FIM
} arrayParsedZip codeBr.push(obJson);
}
jsonZip code = []; }
});
});
});};
返回arrayParsedZip codeBR;}
嗯,看来你正试图读取循环周期的文件,然后,但在一个异步的方式。第一个问题,就是为什么异步读取这些文件?您可以随时同步的方式阅读:
VAR数据= fs.readFileSync(FNAME,编码);
顺便说一句,如果你想阅读异步,并保持了......循环中,您需要像一个承诺,或者定时等待或更复杂的同步机制。
您可以保持它的简单,无需使用任何其他包/这样的模块:
/ **
* Promise.All
* @参数项目对象的数组
* @参数块功能块(项目,指标,解决,拒绝)
* @参数进行功能块成功
* @参数失效功能衰竭块
* @example promiseAll([一,B,C],
函数(项目,指标,解决,拒绝){
MyApp.call(项目,功能(结果){
解决(结果);
},
功能(错误){拒绝(错误); }):
},
功能(结果){//结果汇总 },功能(错误){//错误 }) * @author洛雷托帕里西(loretoparisi在Gmail的点com)
* /
promiseAll:函数(项目,块,完成,失败){
VAR自我=这一点;
VAR承诺= []
索引= 0;
items.forEach(函数(项目){
promises.push(功能(项目一){
返回新希望(函数(解析,拒绝){
如果(块){
block.apply(这一点,[项目,指标,解决,拒绝]);
}
});
}(项目,++指数))
});
Promise.all(承诺)。然后(函数AcceptHandler(结果){
如果(完成)完成的(结果);
},功能的ErrorHandler(错误){
如果(故障)失败(错误);
});
} // promiseAll
所以你可以这样调用它
promiseAll(arrayOfItems,函数(项目,指标,解决,拒绝){
//做一些项目
如果(someSuccessCondOnThisItem){
决心(项目)
}其他{
拒绝(新错误(操作失败))
}
},功能(结果){//汇总结果 的console.log(所有做过%D,results.length);},功能(错误){//错误
的console.log(error.toString());
});
请记住,这是一个非常简单的方法,但在大多数情况下,它通过循环数组时起作用。
下面是在操场上一个简单的例子:
VAR控制台= {\r
日志:功能(S){的document.getElementById(控制台)的innerHTML + = S +< BR />中。}\r
}\r
VAR promiseAll =功能(物品,块,完成,失败){\r
VAR自我=这一点;\r
VAR承诺= []\r
索引= 0;\r
items.forEach(函数(项目){\r
promises.push(功能(项目一){\r
返回新希望(函数(解析,拒绝){\r
如果(块){\r
block.apply(这一点,[项目,指标,解决,拒绝]);\r
}\r
});\r
}(项目,++指数))\r
});\r
Promise.all(承诺)。然后(函数AcceptHandler(结果){\r
如果(完成)完成的(结果);\r
},功能的ErrorHandler(错误){\r
如果(故障)失败(错误);\r
});\r
}; // promiseAll\r
\r
改编= [1,2,3]\r
promiseAll(ARR\r
,函数(项目,指标,解决,拒绝){\r
的console.log(解决项目[+指数+])\r
VAR okCond = TRUE\r
如果(okCond){解析(项目)}其他{拒绝(新错误(项目[+指数+]))}\r
}\r
,功能(结果){//汇总结果\r
的console.log(+ results.length所有的做);\r
}\r
,功能(错误){//错误\r
的console.log(错误);\r
});
\r
< DIV ID =控制台/>
\r
最后,一个完整的异步的例子,说明如何推迟XMLHtt prequest的执行,通过列表循环时。在 ExecutionBlock
呼吁拒绝
和解析
的SimpleRequest响应后,引起了无极调用之前,等待其执行然后
。
VAR控制台= {\r
日志:功能(S){\r
的document.getElementById(控制台)的innerHTML + = S +。< BR />中\r
}\r
}\r
//简单XMLHtt prequest\r
//基于https://davidwalsh.name/xmlhtt$p$pquest\r
SimpleRequest = {\r
调用:function(什么,响应){\r
VAR请求;\r
如果(window.XMLHtt prequest){// Mozilla中,Safari浏览器,...\r
请求=新XMLHtt prequest();\r
}否则如果(window.ActiveXObject){// IE\r
尝试{\r
请求=新的ActiveXObject(MSXML2.XMLHTTP);\r
}赶上(E){\r
尝试{\r
请求=新的ActiveXObject('Microsoft.XMLHTTP');\r
}赶上(E){}\r
}\r
}\r
//状态变化\r
request.onreadystatechange =功能(){\r
如果(request.readyState === 4){//完成\r
如果(request.status === 200){//完成\r
响应(request.responseText)\r
}其他响应();\r
}\r
}\r
request.open(GET,是什么,真正的);\r
request.send(NULL);\r
}\r
}\r
// PromiseAll\r
VAR promiseAll =功能(物品,块,完成,失败){\r
VAR自我=这一点;\r
VAR承诺= []\r
索引= 0;\r
items.forEach(函数(项目){\r
promises.push(功能(项目一){\r
返回新希望(函数(解析,拒绝){\r
如果(块){\r
block.apply(这一点,[项目,指标,解决,拒绝]);\r
}\r
});\r
}(项目,++指数))\r
});\r
Promise.all(承诺)。然后(函数AcceptHandler(结果){\r
如果(完成)完成的(结果);\r
},功能的ErrorHandler(错误){\r
如果(故障)失败(错误);\r
});\r
}; // promiseAll\r
\r
// LP:延迟执行块\r
VAR ExecutionBlock =功能(项指标,解决,拒绝){\r
SimpleRequest.call('http://icanhazip.com/',函数(结果){\r
如果(结果){\r
的console.log(响应[+指数+]+结果);\r
解决(结果);\r
}其他{\r
拒绝(新错误(呼叫错误));\r
}\r
})\r
}\r
\r
改编= [1,2,3]\r
promiseAll(ARR,函数(项目,指标,解决,拒绝){\r
的console.log(制作要求[+指数+])\r
ExecutionBlock(项目,指标,解决,拒绝);\r
},功能(结果){//汇总结果\r
的console.log(所有收到响应+ results.length);\r
的console.log(JSON.stringify(结果));\r
},功能(错误){//错误\r
的console.log(错误);\r
});
\r
< DIV ID =控制台/>
\r
i have a problem with sync using fs.readfile, they are not inicializing at the first time, if i try request again, then i have results. I know i can use promise and i find something useful with Q from Kriskowal.I tried it but without success. I didn´t understand very well how to implement it. If someone can help with this, i will be eternally grateful.
code:
"use strict"
var Q = require('q');
var fs = require('fs');
var arrayZipBand = [];
var jsonZipCode = [];
var arrayParsedZipcodeBr = [];
exports.parse = function(opts) {
if (opts.zipBand.constructor != Array) {
opts.zipBand = [opts.zipBand];
}
if (opts.location.constructor != Array) {
opts.location = [opts.location];
}
if (opts.config === 0) {
opts.zipBand.forEach(function(file) {
fs.readFile(file, 'utf8', function(err, logData) {
if (err) throw err;
let text = logData.toString();
decodeURIComponent(text);
let lines = text.split('\n');
lines.forEach(function(line) {
let parts = line.split('@');
if (parts[1] != undefined) {
let obJson = {
LOC_NU: parts[0],
LOC_CEP_INI: parts[1],
LOC_CEP_FIM: parts[2]
}
arrayZipBand.push(obJson);
}
});
});
});
opts.location.forEach(function(file) {
fs.readFile(file, 'utf8', function(err, logData) {
if (err) throw err;
let text = logData.toString();
decodeURIComponent(text);
let lines = text.split('\n');
lines.forEach(function(line) {
let parts = line.split('@');
if (parts[1] != undefined) {
for (let i = 0; i < arrayZipBand.length; i++) {
if (parts[0] == arrayZipBand[i].LOC_NU) {
jsonZipCode.push(arrayZipBand[i]);
}
}
if (jsonZipCode === undefined) {
throw "Was not possible to find Zipcode for the id " + parts[0];
}
for (let i = 0; i < jsonZipCode.length; i++) {
let obJson = {
LOC_NU: parts[0],
UFE_SG: parts[1],
LOC_NO: parts[2],
MUN_NU: parts[8],
LOC_CEP_INI: jsonZipCode[i].LOC_CEP_INI,
LOC_CEP_FIM: jsonZipCode[i].LOC_CEP_FIM
}
arrayParsedZipcodeBr.push(obJson);
}
jsonZipCode = [];
}
});
});
});
};
return arrayParsedZipcodeBr;
}
uhm it seems you are trying to read files in the loop cycle then, but in a async way. First question, is why async reading those files? You can always read them in sync way:
var data=fs.readFileSync(fname, encoding);
By the way, if you wish to read them async and keep the for...loop you need something like a Promise, or a timed wait or a more complex synchronization mechanism.
You can keep it simple, without using any other packages/modules in this way:
/**
* Promise.All
* @param items Array of objects
* @param block Function block(item,index,resolve,reject)
* @param done Function Success block
* @param fail Function Failure block
* @example
promiseAll(["a","b","c"],
function(item,index,resolve,reject) {
MyApp.call(item,function(result) {
resolve(result);
},
function( error ) { reject(error); }):
},
function(result) { // aggregated results
},function(error) { // error
})
* @author Loreto Parisi (loretoparisi at gmail dot com)
*/
promiseAll: function(items, block, done, fail) {
var self = this;
var promises = [],
index = 0;
items.forEach(function(item) {
promises.push(function(item, i) {
return new Promise(function(resolve, reject) {
if (block) {
block.apply(this, [item, index, resolve, reject]);
}
});
}(item, ++index))
});
Promise.all(promises).then(function AcceptHandler(results) {
if (done) done(results);
}, function ErrorHandler(error) {
if (fail) fail(error);
});
}, //promiseAll
so you can call it like
promiseAll(arrayOfItems, function(item, index, resolve, reject) {
// do something on item
if (someSuccessCondOnThisItem) {
resolve(item)
} else {
reject(new Error("operation failed"))
}
}, function(results) { // aggregated results
console.log("All done %d", results.length);
}, function(error) { // error
console.log(error.toString());
});
Keep in mind that this is a very simplified approach, but in most of cases it works when cycling through arrays.
Here is a simple working example in the playground:
var console = {
log : function(s) { document.getElementById("console").innerHTML+=s+"<br/>"}
}
var promiseAll= function(items, block, done, fail) {
var self = this;
var promises = [],
index = 0;
items.forEach(function(item) {
promises.push(function(item, i) {
return new Promise(function(resolve, reject) {
if (block) {
block.apply(this, [item, index, resolve, reject]);
}
});
}(item, ++index))
});
Promise.all(promises).then(function AcceptHandler(results) {
if (done) done(results);
}, function ErrorHandler(error) {
if (fail) fail(error);
});
}; //promiseAll
arr=[1,2,3]
promiseAll(arr
,function(item,index,resolve,reject) {
console.log("Resolving item[" + index+"]")
var okCond=true
if(okCond) {resolve(item)} else { reject(new Error("item[" + index+"]")) }
}
,function(results) { // aggregated results
console.log("All done of "+results.length);
}
,function(error) { // error
console.log(error);
});
<div id="console"/>
Finally, a complete asynchronous example, showing how to defer execution of a XMLHttpRequest, when cycling through a list. The ExecutionBlock
is calling reject
and resolve
after the SimpleRequest responds, causing the Promise the wait its execution before calling the then
.
var console = {
log: function(s) {
document.getElementById("console").innerHTML += s + "<br/>"
}
}
// Simple XMLHttpRequest
// based on https://davidwalsh.name/xmlhttprequest
SimpleRequest = {
call: function(what, response) {
var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
}
// state changes
request.onreadystatechange = function() {
if (request.readyState === 4) { // done
if (request.status === 200) { // complete
response(request.responseText)
} else response();
}
}
request.open('GET', what, true);
request.send(null);
}
}
//PromiseAll
var promiseAll = function(items, block, done, fail) {
var self = this;
var promises = [],
index = 0;
items.forEach(function(item) {
promises.push(function(item, i) {
return new Promise(function(resolve, reject) {
if (block) {
block.apply(this, [item, index, resolve, reject]);
}
});
}(item, ++index))
});
Promise.all(promises).then(function AcceptHandler(results) {
if (done) done(results);
}, function ErrorHandler(error) {
if (fail) fail(error);
});
}; //promiseAll
// LP: deferred execution block
var ExecutionBlock = function(item, index, resolve, reject) {
SimpleRequest.call('http://icanhazip.com/', function(result) {
if (result) {
console.log("Response[" + index + "] " + result);
resolve(result);
} else {
reject(new Error("call error"));
}
})
}
arr = [1, 2, 3]
promiseAll(arr, function(item, index, resolve, reject) {
console.log("Making request [" + index + "]")
ExecutionBlock(item, index, resolve, reject);
}, function(results) { // aggregated results
console.log("All response received " + results.length);
console.log(JSON.stringify(results));
}, function(error) { // error
console.log(error);
});
<div id="console" />
这篇关于无极如何在这种情况下实施?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!