【React】JS异步执行工具 Promise

2017-12-21  本文已影响0人  晴天mk1992

使用Promise 实现刷新页面、业务代码的先后执行

new Promise((resolve => {
    this.setState({
        key:value
    })
    resolve();
})).then(()=>{
    try {
        this.refs['panel'].handleSearch();
    } catch (error) {
        console.error(error.message)
    }
});

自定义封装(方便调用)

/**
 *
 * @param service
 * @param then
 */
requestService = (config) => {
    new Promise((resolve) => {
        resolve(config.request());
    }).then((response) => {
        config.then(response)
    });
}

自定义调用

this.requestService({
    request: () => {
        this.setLoading(true);
        let result = requestInterface()
        return result
    },
    then: (result) => {
        this.setLoading(false);
        this.handleResponse(result);
        this.refreshData();
    }
});
上一篇下一篇

猜你喜欢

热点阅读