相关文章推荐
不敢表白的海豚  ·  【转】Java ...·  3 年前    · 
豪气的创口贴  ·  ListBox 类 ...·  3 年前    · 

习惯了C语言系的思维方式,刚接触Node.js,它的异步处理让我头大。
写代码遇到这么一个场景,需要循环对一个数组中的元素进行处理,全部处理完成后再执行一个last操作。但是JS的异步特性会使这个last语句先执行,所以花点时间研究研究forEach。
Talk is cheap. Show me the code.

forEach 用法

forEach用于对数组结构进行遍历,看到有人说forEach底层是用for实现的,没深究,起码效果上看是一样的。forEach的回调函数3个参数分别是:值、序号和原数组。序号从0开始。

(() => {
    let arr = [2, 3, 1];
    arr.forEach(function (value, index, array) {
        console.log(value);
        console.log(index);
        console.log(array);
        console.log('-----');
    });
})();

Output

[ 2, 3, 1 ] ----- [ 2, 3, 1 ] ----- [ 2, 3, 1 ] -----

从结果上看forEach多次循环之间是同步的,也就是说都是按顺序执行的。但是一想到它是JS就感觉不可能同步的。。可以验证一下。

forEach 异步处理多次循环

这次在forEach加个定时任务,每次循环操作都延时value相关的时间,模拟比较耗时的操作。

(() => {
    let arr = [2, 3, 1];
    arr.forEach(function (value, index, array) {
        setTimeout(function () {
            console.log(value);
        }, value*100);
    });
})();

Output

从结果可以看出耗时最短的任务先完成,每次循环的任务并不是按循环的先后顺序执行的,也就是说异步处理多次循环。

forEach 上下文也是异步执行

回到开始说到的问题了,且不管多次循环是不是按顺序执行,我需要forEach中的所有任务都完成后执行一条数据来通知我任务全部完成了。

(() => {
    let arr = [2, 3, 1];
    arr.forEach(function (value, index, array) {
        setTimeout(function () {
            console.log(value);
        }, value*100);
    });
    console.log('All the work is done');
})();

Output

All the work is done

从结果来看,上下文的语句也不是同步的,forEach循环中的任务没有完成就通知所有任务都完成了,显然不符合预期。
针对这个问题看了好多个博客,都没有找到合适的解决方法,最后只能想到用Promise.all来勉强实现这个功能。

Promise.all 实现 forEach 上下文语句同步处理

把上面的代码改成Promise.all的结构。每个循环中执行结束调用resolve(),我们知道Promise.all的then函数,只有所有的Promise都执行完成才会触发,这样好像能满足我们的需求。

(() => {
    let arr = [2, 3, 1];
    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');
})();

Output

All the work is done

从结果来看,满足了我们的需求。

可能还存在的问题

想到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];   // 10
    arr= arr.concat(arr);   // 2^1 * 10
    arr= arr.concat(arr);   // 2^2 * 10
    arr= arr.concat(arr);   // 2^3
    arr= arr.concat(arr);   // 2^4
    arr= arr.concat(arr);   // 2^5
    arr= arr.concat(arr);
    arr= arr.concat(arr);
    arr= arr.concat(arr);
    arr= arr.concat(arr);
    arr= arr.concat(arr);   // 2^10
    arr= arr.concat(arr);
    arr= arr.concat(arr);
    arr= arr.concat(arr);
    arr= arr.concat(arr);
    arr= arr.concat(arr);   // 2^15
    arr= arr.concat(arr);
    arr= arr.concat(arr);	// 2^17 * 10
//  arr= arr.concat(arr);   // 2^18 * 10
    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