0

I would need for an app to bind a this parametter to a Promise, and i can't find how to do this ...

Here is exactly what i want to do:

var myPromise = new Promise((resolve, reject) => {
    console.log(this);
});
myPromise.then();

I would like "this" to have the value i want. Since i need to define it outside.

Is it possible ?

Note: I want to avoid this solution:

var myPromise = (that) => {
    return new Promise((resolve, reject) => {
         console.log(that);
    })
}
myPromise().then();

Since it makes the code really heavy.

1
  • I don't get your question. If the code you presented already does exactly what you want, then what's the problem?
    – Bergi
    Apr 24, 2016 at 11:29

1 Answer 1

4

Arrow function has a lexical "this" binding, thus it gets "this" from the enclosing context.

If you'd like to have bind specified by, you should try using bind. Example code:

new Promise(function(resolve, reject) {
    console.log(this);
}.bind(that));
2
  • Hi Jakub Rożek. Thank you for your answer. But to me it's not working. I tried this: var that = "bloublou"; var p = new Promise(function(resolve, reject) { console.log(this); }.bind(that)); p.then(); But it's logging the promise, and not the string "bloublou"
    – Poyoman
    Apr 30, 2016 at 9:10
  • 1
    Works fine here. Are you sure you read the proper line in the console? It returns the Promise, yet the output of console is the desired "this". However you must notice one thing, if you pass the string using bind, you must do console.log(""+this); Apr 30, 2016 at 9:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.