cheungseol / cheungseol.github.io

2 stars 0 forks source link

callback && promise && async/await #19

Open cheungseol opened 6 years ago

cheungseol commented 6 years ago

callback

 export  default safeRequest(safeRequestContent, res => {
            if (res.err_no === 1) {
                fallback(res.err_tip);
            } else {
                callback(res);  // 服务端返回结果,包含 err_no 不等于 0 
            }
        });

safeRequest({
            url: api,
            method: 'get',
            params: {
                offset: this.state.offset,
                count: CHUNK_SIZE
            },
            body_content_type: 'json',
            callback: res => {
            },
            fallback: error => {

            }
        });

promise

safeRequest({
            url:  api,
            method: 'get',
            params: {
                offset: this.state.offset,
                count: CHUNK_SIZE
            },
            body_content_type: 'json',
        }).then(res=>{
            console.log(res);
        }).catch(e=>{
            console.log('999', e);
        });

async/await


let onlineAjaxPromise = new Promise(function (reslove, reject) {
            bridgeController.safeRequest(safeRequestContent, res => {
                if (res.err_no === 1) {
                    reject(res.err_tip);
                } else {
                    reslove(res);  // 服务端返回结果,包含 err_no 不等于 0 
                }
            });
        });

return onlineAjaxPromise;

async fetchData() {
        try {
            const res = await safeRequest({
                url: '/score_task/v1/apprentice/page_data/',
                method: 'get',
                params: {
                    offset: this.state.offset,
                    count: CHUNK_SIZE
                },
                body_content_type: 'json',
            });
            console.log(6666, res);
        } catch (err) {
            console.log(err);
            alert(JSON.stringify(err));
            this.setState({ fetchStatus: 'error' });
            ToutiaoJSBridge && jsBridge.toast('网络错误');
        }
    }

this.fetchData();