简体   繁体   中英

returning ES6 promise from constructor - binding this

I want to do

X.prototype.f = function() {
    return new Promise(
        function(resolve, reject) {
           if (this.f1()==0) resolve();
           ...

however this (that is the X instance) is not defined inside the promise constructor. I understand I need to bind this somehow but not sure how to proceed ?

As you're using es6, why aren't you using es6?

X.prototype.f = function() {
    return new Promise((resolve, reject) => {
       if (this.f1()==0) resolve();
    });
}

You can assign this to another variable inside the function

X.prototype.f = function() {
    var self = this;
    return new Promise(
        function(resolve, reject) {
           if (self.f1()==0) resolve();
           ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM