First, the realization of ideas
The characteristics Promise.race we add Promise.race which two tasks, one is the normal web request tasks A, another task B is network latency, network latency can make use of setTimeout methods.
This time there will be three conditions:
1.A task is completed (assuming that 8 seconds timeout) within 8 seconds, the normal end Promise.race task.
2. A task over eight seconds still not completed by the end of the automatic timer interrupt task B Promise.race.
3. abnormal, Promise.race automatically end.
For the above three cases to design the network timeout scheme.
This time there will be three conditions:
1.A task is completed (assuming that 8 seconds timeout) within 8 seconds, the normal end Promise.race task.
2. A task over eight seconds still not completed by the end of the automatic timer interrupt task B Promise.race.
3. abnormal, Promise.race automatically end.
For the above three cases to design the network timeout scheme.
Second, the code
HttpUtil.js
// define delay function const Delay = (= timeOut . 8 * 1000 ) => { return new new Promise ((Resolve, Reject) => { the setTimeout (() => { Reject ( new new Error ( ' network time ' ); }, timeOut); }) } // FETCH request network const fetchPromise = (Method, URL, formData) => { return new new Promise ((Resolve, Reject) => { FETCH (URL, { Method: Method, body: formData }). then ((response)=> { if (response.ok) { return response.json(); } else { reject(new Error('服务器异常')); } }).then((responseJson) => { resolve (responseJson); }).catch((err) => { reject(new Error(err); }) }) } //race任务 const _fetch = (fetchPromise, timeout) => { return Promise.race([fetchPromise,delay(timeout)]); } //post const HttpPost = (url, formData,timeout = 8*1000) =>{ return _fetch(fetchPromise('POST', url, formData), timeout); }; //get const HttpGet = (url,timeout = 8*1000) =>{ return _fetch(fetchPromise('Get', url), timeout); };
export {HttpPost ,HttpGet}
reference:
https://www.jianshu.com/p/2df7c6e3b3c3
This blog address: wukong1688
This article Original Address: https://www.cnblogs.com/wukong1688/p/10963004.html
Please reprint famous source! Thank you ~ ~