Nodejs Calling Function From Within A Function
I have 3 methods exports.getImageById = function (resultFn, id) { ... } exports.getCollectionById = function (resultFn, id) { } in the third method I want to call both methods e
Solution 1:
When you call this.getCollectionById
passing it a callback, the callback doesn't have access to the same this
The simplest solution is to save this
as a local variable.
exports.getCollectionImages = function (resultFn, collectionId) {
var arr = newArray();
var me = this; // Save thisthis.getCollectionById( // fine, 1st callfunction (result) {
var images = result.image;
for (var i = 0; i < images.length; i++) {
// Use me instead of this
me.getImageById(function (result1) { // error, 2nd call
arr[i] = result1;
}, images[i]);
}
}, collectionId);
resultFn(arr);
}
Solution 2:
The value of this
inside the inner function is not the same object as outside, because it's determined depending on how the function is called. You can find a detailed explanation in the MDN article on this
.
One of the ways to solve it is by keeping a reference to the outer this
in another variable such as that
:
var that = this;
this.getCollectionById( // fine, 1st callfunction (result) {
var images = result.image;
for (i = 0; i < images.length; i++) {
that.getImageById(function (result1) { // 2nd call
arr[i] = result1;
}, images[i]
);
}
}
, collectionId
);
Post a Comment for "Nodejs Calling Function From Within A Function"