栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在对象值的异步for循环完成执行后如何调用函数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在对象值的异步for循环完成执行后如何调用函数

这可以在普通JS中完成,但是我建议使用

async
模块,它是用于处理Node.js中异步代码的最流行的库。例如,使用
async.each

var async = require('async');var courseIds = Object.keys(courses);// Function for handling each course.function perCourse(courseId, callback) {    var course = courses[courseId];    // do something with each course.    callback();}async.each(courseIds, perCourse, function (err) {    // Executed after each course has been processed.});

如果要使用每次迭代的结果,则

async.map
类似,但是将结果数组传递给回调的第二个参数。

如果您喜欢香草JS,则可以代替

async.each

function each(list, func, callback) {    // Avoid emptying the original list.    var listCopy = list.slice(0);    // Consumes the list an element at a time from the left.    // If you are concerned with overhead in using the shift    // you can accomplish the same with an iterator.    function doOne(err) {        if (err) { return callback(err);        }        if (listCopy.length === 0) { return callback();        }        var thisElem = listCopy.shift();        func(thisElem, doOne);    }    doOne();}

(摘自我前段时间写的要点)

我强烈建议您使用异步库。异步很容易编写,类似

async.auto
的功能非常出色。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/417979.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号