首页 > async.map异步查询数据后render界面

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

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的值


正确调用:

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);
})

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里


function(item, callback){
    // 是不是这个函数里面忘记调用callbacks?
}

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

【热门文章】
【热门文章】