首页 > 解决方案 > 即使在推送数据后,节点 js 也会得到空白 obj

问题描述

在这里,我试图将数据推送到我的数组中,但它始终是空的。

read_file: ['pass_fileData', function (result, cb) {
    let obj = [];
    async.each(result.pass_fileData, function (item) {
        knex
        .select('xxxxx')
        .from('xxxx')
        .innerJoin('xxxx', 'xxxx', 'xxx')
        .where('xxxxx', '=', item)
        .then(function (data) {
            obj.push(data) // here I am pushing data to array
        })
        .catch(function (err) {
            cb(err);
        })
    })
    cb(null, obj)
}]

CB(null, obj)我没有得到任何数据,但是当我控制台时,我从 db 获取数据。

标签: javascriptnode.jsknex.jsasync.js

解决方案


因为您的功能是异步的。这意味着当你的回调cb(null, obj)被调用时,数据还没有。您希望在执行每个异步函数后调用回调。

async.each可以接受第三个参数,这是一个回调,一旦函数完成就会被调用。

您的代码应如下所示:

read_file: ['pass_fileData', function (result, cb) {
    let obj = [];
    async.each(result.pass_fileData, function (item, callback) {
        knex
        .select('xxxxx')
        .from('xxxx')
        .innerJoin('xxxx', 'xxxx', 'xxx')
        .where('xxxxx', '=', item)
        .then(function (data) {
            obj.push(data) // here I am pushing data to array
            callback() // Iteratee callback
        })
        .catch(function (err) {
            callback(err); // Iteratee callback
        })
    }, function (err) { // end callback
      cb(err, obj) // Your callback that takes the obj
    })
}]

推荐阅读