ReactNativeUtil icon indicating copy to clipboard operation
ReactNativeUtil copied to clipboard

可以取消的promise fetch

Open wuyunqiang opened this issue 7 years ago • 0 comments

export default function makeCancelable(promise){
    let hasCanceled_ = false;
    const wrappedPromise = new Promise((resolve, reject) => {
        promise.then((val) =>
            hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
        );
        promise.catch((error) =>
            hasCanceled_ ? reject({isCanceled: true}) : reject(error)
        );
    });
    return {
        promise: wrappedPromise,
        cancel() {
            hasCanceled_ = true;
        },
    };
}

this.cancelable = makeCancelable(fetch('url')));
        this.cancelable.promise
            .then((response)=>response.json())
            .then((responseData)=> {          
                console.log(responseData);                            
            }).catch((error)=> {
                console.log(error); 
            });

//使用
componentWillUnmount() {      
  this.cancelable.cancel();
}

wuyunqiang avatar Feb 27 '18 02:02 wuyunqiang