从承诺中调用函数?

时间:2018-03-20 14:20:11

标签: javascript

我需要在functionA

中的promise中调用functionB
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 
                });
        });
    }

但是我收到了这个错误:

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

这是在React组件中,但我认为这不重要。

3 个答案:

答案 0 :(得分:5)

使用这样的箭头函数,常规函数有自己的上下文(' this'),而箭头函数采用其父上下文:



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 :)
                });
        });
    }




答案 1 :(得分:0)

您需要在构造函数中绑定函数('this'未定义)

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

答案 2 :(得分:0)

里面.then()它在不同的范围内。分配"这个"提前变量然后在.then函数中使用它就可以了。

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();
                });
        });
    }