javascript - 即使在推送数据后,节点 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 获取数据。
解决方案
因为您的功能是异步的。这意味着当你的回调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
})
}]
推荐阅读
- c++ - C ++递归查找数组的最小值
- python - 启用防火墙时端口扫描失败
- mobile - 更改文本字段的大小和行为
- node.js - redux 中的 DELETE 请求
- python - 为什么用 `@abstractmethod` 装饰的方法 **NOT** 有一个为 True 的 `__isabstractmethod__` 属性?
- java - JavaFXfocusedProperty().addListener 重构代码
- jquery - 如何在 Angular 中使用 jQuery hide boostrap4 Modal?
- ios - 自定义 UIView 一开始只覆盖屏幕的一部分
- algorithm - 如何用实数坐标计算像素的颜色
- node.js - 带有 Express 的简单子域