I am not sure if what I am expecting is correct or not, but if Promise
is like any other JavaScript class, it should have a this
context.
But the following code surprises me.
var promise = new Promise(function (resolve, reject) {
console.log(this === window); // Prints true
});
Am I missing the concept of native Promises here?
My objective is to attache some property to the promise object while creating it, and be able to access it later.
I know the callback function passed in the Promise
isn't in any context and would be called just like a plain function. But is there a way to attach the property to each promise returned?
this.someProp = someobj.returnVal();
More Info
Basically, I am making an ajax request inside the promise, and I want to store the request object in the promise so that I can use it to abort
the request when I want. by adding a polyfill abort
to the Promise.prototype
Here's the actual code.
var _request;
const promise = new Promise(function (resolve, reject) {
this._request = superagent.get(url)
.end((error, res) => { resolve(res); }); // What I expect to work
_request = superagent.get(url)
.end((error, res) => { resolve(res); }); // But I have no this context
});
Promise.prototype.abort = function () {
this._request.abort(); // Can't do this
}