与axios的并发请求

时间:2017-03-12 23:09:38

标签: javascript reactjs promise es6-promise axios

在React应用程序中,我需要从表单发布数据。该帖子创建了一个新的仪表板对象。完成后,我需要立即更新组件中的选择下拉列表以包含新添加的仪表板名称。 axios documentation表示应该这样做:

index.html

所以这就是我所做的:

function getUserAccount() {
   return axios.get('/user/12345');
}

function getUserPermissions() {
   return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));

表单提交时调用saveAndRepopulate。

问题是我收到以下错误:

class DashboardForm extends Component {

saveDashboard() {
    var siteId = this.state.siteId;
    var self= this;
    return axios.post('/path/to/save/dashboard' + siteId + '/dashboards', {
        slug: this.refs.dashboardUrl.value,
        name: this.refs.dashboardName.value,
    }).then(function (response) {
        self.setState({
            dashboardId: response.data.dashboardId,
            dashboardName: response.data.dashboardName,
            submitMessage: (<p>Successfully Created</p>)
        });
        self.setUrl(siteId, response.data.dashboardId);

    }).catch(function (error) {
        console.log(error);
        self.setState({
            submitMessage: (<p>Failed</p>)
        });
    });
}

getAllDashboards(){
    var self = this;
    self.setState({siteId: this.props.selectedSiteID});
    var getDashboardsPath = "path/to/get/dashboards/" + self.props.selectedSiteID + "/dashboards";

    axios(getDashboardsPath, {
        credentials: 'include',
        method: 'GET',
        cache: 'no-cache'
    }).then(function (response) {
        return response.data.dashboards;
    }).then(function (arrDashboards) {   //populate options for the select
        var options = [];
        for (var i = 0; i < arrDashboards.length; i++) {
            var option = arrDashboards[i];
            options.push(
                (<option className="dashboardOptions" key={option.dashboardId} value={option.slug}>{option.name}</option>)
            );
        }
        self.setState({
            options: options
        });
    });
}

saveAndRepopulate() {
    axios.all([saveDashboard(), getAllDashboards()])
        .then(axios.spread(function (savedDashboard, listOfDashboards) {
            // Both requests are now complete
        }));
     }

}

我已经尝试过了

error    'saveDashboard' is not defined             no-undef
error    'getAllDashboards' is not defined          no-undef

然后我得到了

语法错误:预期的意外令牌((175:13)

function saveDashboard() { 

如何调用这两个功能?另外,我是否需要将单个调用中的promise(.then)更改为saveAndPopulate?

非常感谢任何指导。

1 个答案:

答案 0 :(得分:0)

首先,正如@Jaromanda X指出的那样,您应该使用this调用内部组件函数,并且需要将这些函数绑定到this。有多种方法可以做到这一点,其中一种方法是将它绑定在组件构造函数中,如:

this.saveDashboard = this.saveDashboard.bind(this)

其他好处是在saveDashboard()getAllDashboards()

内返回axios调用