想到JS异步特性,突然发现可能这个方法还存在个问题。
这里每次 forEach 刚进入就对 Promise 数组进行了赋值操作,这个操作时间应该非常短,循环3次都赋值完成后才调用最后的Promise.all语句。
但是如果这个数组非常大,这个循环赋值的操作非常耗时间的话,假如只完成了一半的赋值操作,那么执行最后这个 Promise.all 的时候传入的 Promise 数组可能并不是包含所有 Promise 的数组。
这样的话 Promise.all 等待的就只有一半的操作,Promise.all 等待的时候,这个数组后面被赋值的 Promise 不知道会不会被等待。
刚接触JS不明白实现机制,只能实验来验证一下是否存在这个问题。接下来用把这个数组弄大一些,请原谅我用最傻瓜式的方式搞大它。
(() => {
let arr = [2, 3, 1, 2, 3, 1, 2, 3, 1, 2];
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
arr= arr.concat(arr);
console.log(arr.length);
let proArr = [];
arr.forEach(function (value, index) {
proArr[index] = new Promise(function (resolve) {
setTimeout(function () {
console.log(value);
resolve();
}, value*100);
});
});
Promise.all(proArr).then(()=>{
console.log('All the work is done');
console.log(arr.length);
}).catch(function (err) {
console.log(err);
})();
经过测试在我这个电脑上当数组长度为2^18 * 10的时候,Promise报错 RangeError: Too many elements passed to Promise.all。
当数组长度为2^17 * 10 即2621440的时候,会正常运行。测试了几次,最后的执行命令输出的All the work is done始终在最后输出(因为终端缓冲区太小,所以使用node xx.js > log.txt重定向的方式把输出结果重定向到文件查看)。当然应用中也不会有这么大的数组,从结果看的话,就是实际应用中不存在上面考虑可能出现的问题。
也就是说可以用 Promise.all 实现 forEach 上下文语句同步处理。
如果有对JS理解透彻的朋友看出了上文的问题,欢迎指教。
习惯了C语言系的思维方式,刚接触Node.js,它的异步处理让我头大。写代码遇到这么一个场景,需要循环对一个数组中的元素进行处理,全部处理完成后再执行一个last操作。但是JS的异步特性会使这个last语句先执行,所以花点时间研究研究forEach。Talk is cheap. Show me the code.forEach 用法forEach用于对数组结构进行遍历,看到有人说forEa...
博客已经迁移到www.imyzf.com,本站不再更新,请谅解!
node里几乎所有用到回调函数的地方,都是异步的,回调函数后面的代码很可能比回调函数中的代码后先执行,特别是数据库操作。当然,node也提供了同步版本的函数,例如文件操作,fs.readFileSync()是fs.readFile()的同步版本。
那么问题来了,forEach()是不是异步的呢?按理说,没有加Sync,...
const path=require('path');
function travel(dir,callback){
fs.readdirSync(dir).forEach((file)=>{
var pathname=path.join(dir,file)
if(fs.statSync(pathname).isDirectory()){
travel(pathname,callback)
}else{
async.each():for循环中牵涉到异步变同步,经常使用。
async.waterfull(): 同步执行,function之间有数据交互,上一个function的输出,可作为下一个function的输入。
async.ser...
最近用nodejs做了个针对某网站的小爬虫。干坏事得低调对吧,不能同时开太多的网络访问,结果各种回调/循环虐的心力交瘁。
经过了n次的百度\哥哥后终于拼出了自己要的功能。不敢独享分享出来以供大家参考。
废话不多说直接上代码
var async = require("async"); var citysUrl=[]; var urlsArray=[];
async.e...
NodeJieba "结巴"分词的Node.js版本Introduction
NodeJieba只是CppJieba简单包装而成的node扩展,用来进行中文分词。
详见NodeJiebaBlogInstallnpm install nodejieba
因为npm速度很慢而且经常因为墙的原因出现莫名其妙的问题,在此强烈建议使用cnpm,命令如下:npm --registry=http://r.cnpmjs.org install nodejieba默认分词算法初始化var segment = require("nodejieba");
segment.loadDict("./node_modules/nodejieba/dict/jieba.dict.utf8", "./node_modules/nodejieba/dict/hmm_model.utf8");阻塞式调用var wordList = segment.cutSync("阻塞模式分词"); if (wordList.constructor == Array) // just for tutorial, this is always be true {
wordList.forEach(function(word) { console.log(word);
}非阻塞式调用segment.cut("非阻塞模式分词", function(wordList) {
wordList.forEach(function(word) { console.log(word);
});初始化var segment = require("nodejieba");
segment.queryLoadDict("./node_modules/nodejieba/dict/jieba.dict.utf8", "./node_modules/nodejieba/dict/hmm_model.utf8");阻塞式调用var wordList = segment.queryCutSync("阻塞模式分词"); if (wordList.constructor == Array) // just for tutorial, this is always be true {
wordList.forEach(function(word) { console.log(word);
}非阻塞式调用segment.queryCut("非阻塞模式分词", function(wordList) {
wordList.forEach(function(word) { console.log(word);
具体用法可以参考 test/segment.js test/query_segment.jsTesting
在node v0.10.2下测试通过http://cppjieba-webdemo.herokuapp.com/ (chrome is suggested)ThanksJieba中文分词
标签:nodejieba
访问参数 你可以通过process.argv来访问到命令行参数,它是一个包含下列内容的数组: [ nodeBinary, script, arg0, arg1, … ] 也就是说,第一个参数是从process.argv[2]开始的,你可以像下面这样遍历所有的参数: 代码如下: process.argv.slice(2).forEach(function (fileName) { … }); 如果你想对参数做更复杂的处理,可以看一下Node.js模块nomnom和optimist.下面,我们会多次用到文件系统模块: 代码如下: var fs = require(‘fs’); 读取一个文本
const fs = require('fs');
const Docx = require('docx');
const fontkit = require('fontkit');
const docx = new Docx();
const file = fs.readFileSync('example.docx');
docx.load(file);
const paragraphs = docx.getParagraphs();
paragraphs.forEach((paragraph) => {
const runs = paragraph.getRuns();
runs.forEach((run) => {
const font = fontkit.openSync(run.getFont().getFontPath());
console.log(`Text: ${run.getText()}, Font: ${font.familyName}`);
请注意,您需要安装docx和fontkit模块,可以使用npm命令进行安装:
npm install docx fontkit