[英]nodejs - pass global variable to promise callback in parse
consider this code 考虑这个代码
for (var i = 0; i < data.length; i++){
query.equalTo("objectId",data[i].id).first().then(
function(object){
object.set("username", data[i].username);
object.save();
}
);
}
in this example data[i]
inside the then callback
is the last element of the array 在此示例中,
then callback
内的data[i]
是数组的最后一个元素
consider this 2nd example that normally work in javascript world 考虑通常在javascript世界中工作的第二个示例
assume we use some API which connect to mongodb and has function called update 假设我们使用一些连接到mongodb的API并具有称为update的功能
for (var i = 0; i < data.length; i++){
query.eq("_id",data[i].id).update(data[i].username);
}
eq
returns the object, update
updates that object and save it. eq
返回对象, update
更新该对象并保存。
will it not be awesome if something like this is possible ... (not sure if it will also even work) 如果这样的事情可能发生,那会不会很棒……(不确定它是否还会起作用)
for (var i = 0; i < data.length; i++){
query.equalTo("objectId",data[i].id).first().then(
function(object, data[i]){
object.set("username", data.username);
object.save();
}
);
}
This actually doesn't work only because of scoping var
. 实际上,仅因为对
var
进行作用域设置,这实际上不起作用。 You can get the sample running as desired just by: 您可以通过以下方式按需运行示例:
a) using let
instead of var
a)使用
let
代替var
b) creating a new scope for i
(this is what let
basically does). B)创建一个新的领域
i
(这是什么let
基本一样)。 (In the anonymous fn, I used ii
instead of i
just for clarity. i
would also work): (在匿名fn中,为清楚起见,我使用
ii
代替了i
。 i
也可以工作):
for (var i = 0; i < data.length; i++){
(function(ii) {
query.equalTo("objectId",data[ii].id).first().then(
function(object){
object.set("username", data[ii].username);
object.save();
}
);
})(i)
}
the best way to solve this problem with parse
is to use recursivity 解决这个问题的最好方法
parse
是使用递归性
...
var do = function(entries, i){
if (entries[i]){
let user = data[i];
query.equalTo("objectId", user.id).first().then(
function(object){
object.set("username", user.username);
object.save();
}
).then(
function(){
return do(entries, i + 1);
}
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.