I'm facing a problem since this morning.
WHAT I HAVE
Basically, I have a simple class, with an array of files to register:
function MyClass() {
this.filesToRegister = [
{
"fileName": "http://tny.im/azk"
},
{
"fileName": "http://tny.im/azk"
}
];
}
I have also a simple function, _contextFunction()
which takes a single fileToRegister
entry:
MyClass.prototype._contextFunction = function(fileToRegister) {
return new Promise((resolve, reject) => {
logger.info(typeof this.filesToRegister);
logger.info('current file: ' + fileToRegister);
return resolve();
});
};
Note that this function MUST access to the context (the this
), it's mandatory, and I can't change that.
Finally, I have a utility method, processArray()
, that can apply a function on each item of an array, all done synchronously:
MyClass.prototype.processArray = function(array, fn) {
let results = [];
return array.reduce((p, item) => {
return p.then(() => {
return fn(item).then((data) => {
results.push(data);
return results;
}).catch(err => console.log(err));
});
}, Promise.resolve());
};
WHAT I TRY TO DO
I use this utility method to apply _contextFunction()
on each item of the filesToRegister
array:
this.processArray(this.filesToRegister, this._contextFunction);
It works without problem and execute this._contextFunction()
on each item of this.filesToRegister
.
WHAT THE PROBLEM IS
BUT, when I try to log typeof this.filesToRegister
in _contextFunction()
, the result is undefined
... After several tests, I concluded that nothing in the context is accessible (neither context attributes nor context methods).
However, if I execute this._contextFunction()
without the processArray()
method, I can access to the context (both context attributes and context methods).
WHAT I THINK
My guess is that the problem comes from the processArray()
method, but I don't see where... I tried to log typeof this.filesToRegister
right in the processArray()
method, and it works...
To conclude:
processArray()
IS able to access to the context.this._contextFunction()
launched 'standalone' IS able to access to the context.this._contextFunction()
launched byprocessArray()
IS NOT able to access to the context.
Can anyone help me? Thanks