@@ -3,16 +3,58 @@ import request from 'request'
33import { debugRequest } from './env'
44// import fs from 'fs'
55
6- const fatchData = ( url , method , options , callback ) => request ( url , {
7- method,
8- headers : options . headers ,
9- Origin : options . origin ,
10- data : options . data ,
11- json : options . format === undefined || options . format === 'json' ,
12- } , ( err , resp , body ) => {
13- if ( err ) return callback ( err , null )
14- callback ( null , resp , body )
15- } )
6+ const fatchData = ( url , method , options , callback ) => {
7+ console . log ( '---start---' , url )
8+ return request ( url , {
9+ method,
10+ headers : options . headers ,
11+ Origin : options . origin ,
12+ data : options . data ,
13+ // timeout: 5000,
14+ json : options . format === undefined || options . format === 'json' ,
15+ } , ( err , resp , body ) => {
16+ if ( err ) return callback ( err , null )
17+ console . log ( '---end---' , url )
18+ callback ( null , resp , body )
19+ } )
20+ }
21+
22+ export const httpFatch = ( url , options = { method : 'get' } ) => {
23+ let requestObj
24+ let cancelFn
25+ const p = new Promise ( ( resolve , reject ) => {
26+ cancelFn = reject
27+ debugRequest && console . log ( `\n---send request------${ url } ------------` )
28+ requestObj = fatchData ( url , options . method , options , ( err , resp , body ) => {
29+ // options.isShowProgress && window.api.hideProgress()
30+ debugRequest && console . log ( `\n---response------${ url } ------------` )
31+ debugRequest && console . log ( JSON . stringify ( body ) )
32+ requestObj = null
33+ cancelFn = null
34+ if ( err ) {
35+ console . log ( err )
36+ if ( err . code === 'ETIMEDOUT' ) {
37+ const { promise, cancelHttp } = httpFatch ( url , options )
38+ obj . cancelHttp = cancelHttp
39+ return promise
40+ }
41+ }
42+ resolve ( resp )
43+ } )
44+ } )
45+ const obj = {
46+ promise : p ,
47+ cancelHttp ( ) {
48+ console . log ( 'cancel' )
49+ if ( ! requestObj ) return
50+ cancelHttp ( requestObj )
51+ cancelFn ( new Error ( '取消http请求' ) )
52+ requestObj = null
53+ cancelFn = null
54+ } ,
55+ }
56+ return obj
57+ }
1658
1759/**
1860 * 取消请求
0 commit comments