node.js - async.map异步查询数据后render界面

 淘宝杂谈网z 发布于 2022-11-02 16:33
exports.index = function(req, res, next) {
    var result = {};
    var getData = [
        {
            shcema: Car,
            example: 'car_list'
        },
        {
            shcema: Brand,
            example: 'brands'
        }
    ]          
    async.map(getData, function(item, callback){
        // 给result赋值
        // ……
    }, function(err,r){
        // 最终回调渲染无效
        res.render('index', result);
    })

};

如题:在回调里面render界面无效,在map函数下面又拿不到result的值

3 个回答
  • 正确调用:

    async.map(getData, function(item, callback){
        item.schema.find({},function(err, res){
            callback(null, data[item.examples] = res || []);
        })
    },function(err,result){
        if(err){
            console.log(err);
        } 
        res.render('index', data);
    })
    2022-11-04 14:49 回答
  • var getData = [{
            shcema: 'Car',
            example: 'car_list'
        }, {
            shcema: 'Brand',
            example: 'brands'
        }
    ]
    async.map(getData, (item, callback) => {
        setTimeout(function() {
            console.log(item.shcema);
            callback(null, [item.shcema, item.example]);
        }, 1000);
    }, (err,r) => {
        console.log(r); // [ [ 'Car', 'car_list' ], [ 'Brand', 'brands' ] ]
    });

    map会将所有的结果将汇总到最终的callback里

    2022-11-04 14:49 回答
  • function(item, callback){
        // 是不是这个函数里面忘记调用callbacks?
    }

    callback一定要去调用,否则下面的function(err, r)就永远不会执行。

    2022-11-04 14:50 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有