[英]Why is the following _.map function returning nothing?
I created a function to find objects: 我创建了一个函数来查找对象:
store.js store.js
store.find = () => {
const query = new Parse.Query(Document)
return query.find()
}
That I'm using like this (and assigning the value to this.documents
): 我正在这样使用(并将值分配给
this.documents
):
main.js main.js
store.find().then((results) => {
this.documents = _.map(results, (result) => {
return result.toJSON()
})
})
It works. 有用。 But the
store.find().then( ...)
part is repeated many times in main.js
so I turned it into a function: 但是
store.find().then( ...)
部分在main.js
重复了很多次,所以我将其变成了一个函数:
store.js store.js
store.fetch = (documents) => {
return store.find().then((results) => {
documents = _.map(results, (result) => {
return result.toJSON()
})
})
}
Which I use like this: 我这样使用:
main.js main.js
store.fetch(this.documents)
But nothing is being assigned to this.documents
and there are no error messages. 但是没有任何内容分配给
this.documents
,并且没有错误消息。 What's could be the problem? 可能是什么问题?
NOTE: this.documents
is an array of objects. 注意:
this.documents
是一个对象数组。 Example: 例:
[{
title: this.title,
content: this.content,
}, ...
EDIT: 编辑:
I did this: 我这样做:
store.fetch = (documents) => {
store.find().then((results) => {
documents = _.map(results, (result) => {
return result.toJSON()
})
console.log(documents)
})
}
And documents
is being assigned: 和
documents
被分配:
[Object, Object, Object, ...]
So I think it's just not assigning this array to this.documents
. 因此,我认为这只是没有将此数组分配给
this.documents
。 Maybe variables can't be arguments and be assigned with a value at the same time? 也许变量不能是参数,而不能同时赋值?
You are passing this.documents
as an argument and attempting to modify that property inside the function. 您正在传递
this.documents
作为参数,并试图在函数内部修改该属性。 However, that can't work, because Javascript does not have "pass by reference" . 但是,这不起作用,因为Javascript没有“按引用传递”功能 。 Only "pass by value".
仅“按值传递”。
Instead, you can try passing the object and the property name separately: 相反,您可以尝试分别传递对象和属性名称:
store.fetch = (obj, prop) => {
return store.find().then((results) => {
obj[prop] = _.map(results, (result) => {
return result.toJSON()
})
})
}
store.fetch(this, 'documents')
Try to get your results in a .then
block after store.fetch(this.documents)
. 尝试让你产生一个
.then
经过块store.fetch(this.documents)
And don't forget to store context 并且不要忘记存储上下文
var self = this;
store.fetch(self.documents).then(function () {
console.log(self.documents);
});
Or usign es6 还是usign es6
store.fetch(this.documents).then(() => {
console.log(this.documents);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.