[英]JavaScript: Accessing variable inside callback
I'm trying to use the open-graph plugin in NodeJS to get a preview image for a vine. 我正在尝试使用NodeJS中的开放式图形插件来获取葡萄藤的预览图像。 The OG result is correct, but I can't access result[i] from within the og callback - the variable is undefined. OG结果正确,但是我无法从og回调中访问result [i]-变量未定义。 How can I access result[i] in the OG callback? 如何在OG回调中访问result [i]?
Thing.find(function(err, result) {
for (var i = 0; i < result.length; i++) {
if (result[i].attachment) {
if (result[i].attachment.embed_type == 'vine') {
og(result[i].attachment.embed_url, function(err, meta) {
result[i].attachment.preview_image = meta.image;
result[i].save();
});
}
}
}
});
You need a closure, i
keeps changing because og
is async 您需要关闭,因为og
是异步的,所以i
会不断变化
Thing.find(function(err, result) {
for (var i = 0; i < result.length; i++) {
if ( result[i].attachment &&
result[i].attachment.embed_type == 'vine')
{
(function(res) {
og(res.attachment.embed_url, function(err, meta) {
res.attachment.preview_image = meta.image;
res.save();
});
}(result[i]));
}
}
});
JS does not have block scope . JS没有块作用域 。
There are some ways to work around this problem, like creating a function, for example. 有一些方法可以解决此问题,例如,创建函数。
And, to make it more clear and easily testable, I would put all the result[n]
logic in the other function as well. 而且,为了使其更加清晰和易于测试,我还将所有result[n]
逻辑也放在其他函数中。
var process = function(resultItem) {
if (resultItem.attachment && if (resultItem.attachment.embed_type == 'vine')) {
og(resultItem.attachment.embed_url, function(err, meta) {
resultItem.attachment.preview_image = meta.image;
resultItem.save();
});
}
};
Thing.find(function(err, result) {
for (var i = 0; i < result.length; i++) {
process(result[i]);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.