简体   繁体   中英

Call function from within a promise?

I need to call functionB from within a promise in functionA

constructor(props) {
    super(props);
    this.functionA = this.functionA.bind(this);
    this.functionB = this.functionB.bind(this);
}


functionA(canvas) {
        let data = new FormData();
        canvas.toBlob(function(blob) {
            data.append('data', blob);
            axios
                .post(`https://api.graph.cool/file/v1/${CONST.projectID}`, data, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                })
                .then(function(res) {
                    console.log('res ', res); // res is as expected 
                    console.log('this ', this); // this is null 
                    this.functionB(); // Errors 
                });
        });
    }

However Im getting this error:

Uncaught (in promise) TypeError: Cannot read property 'functionB' of undefined

This is within a React component but I don't think thats important.

Use arrow functions like this, regular functions have their own context ('this') while arrow functions take their parent's context:

 functionA(canvas) { let data = new FormData(); canvas.toBlob(blob => { data.append('data', blob); axios .post(`https://api.graph.cool/file/v1/${CONST.projectID}`, data, { headers: { 'Content-Type': 'multipart/form-data', }, }) .then(res => { console.log('res ', res); // res is as expected console.log('this ', this); // this is not null this.functionB(); // no Error :) }); }); } 

You need to bind the function in your constructor ('this' is undefined)

this.functionB = this.functionB.bind(this);

Inside .then() it's in a different scope. Assigning "this" to a variable ahead of time then using it inside the .then function will do the trick.

constructor(props) {
    super(props);
    this.functionA = this.functionA.bind(this);
    this.functionB = this.functionB.bind(this);
}


functionA(canvas) {
        let data = new FormData();
        let ctrl = this;
        canvas.toBlob(function(blob) {
            data.append('data', blob);
            axios
                .post(`https://api.graph.cool/file/v1/${CONST.projectID}`, data, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                })
                .then(function(res) {
                    console.log('res ', res); // res is as expected 
                    console.log('this ', this); // this is null (expected)
                    console.log('ctrl', ctrl); //this is the controller 
                    ctrl.functionB();
                });
        });
    }

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