获取商户订单信息超时获取
The fetch API started out as a target for criticism because of lack of timeout and request cancelation. While those criticisms could be argued as fair or not, you can't deny that the fetch API has been pretty awesome. As we've always done, if a feature is missing, we can always shim it in.
由于缺少超时和请求取消,因此fetch API最初开始成为批评的目标。 尽管可以对这些批评进行公正或不公正的争论,但您不能否认fetch API非常出色。 正如我们一贯所做的那样,如果缺少某个功能,则可以始终对其进行匀化。
I've recently been thinking about shimming in a fetch timeout and found a good fetch / timeout script here. I've slightly modified it to prevent the fetch call's then and catch callbacks from carrying out their tasks because I believe the timeout should be handled by the shim's Promise:
我最近一直在考虑在获取超时中进行填充,并在此处找到了一个不错的获取/超时脚本 。 我已经对其进行了少许修改,以防止then的fetch调用并catch回调以执行其任务,因为我认为超时应由填充程序的Promise处理:
const FETCH_TIMEOUT = 5000; let didTimeOut = false; new Promise(function(resolve, reject) { const timeout = setTimeout(function() { didTimeOut = true; reject(new Error('Request timed out')); }, FETCH_TIMEOUT); fetch('https://davidwalsh.name/?xx1') .then(function(response) { // Clear the timeout as cleanup clearTimeout(timeout); if(!didTimeOut) { console.log('fetch good! ', response); resolve(response); } }) .catch(function(err) { console.log('fetch failed! ', err); // Rejection already happened with setTimeout if(didTimeOut) return; // Reject with error reject(err); }); }) .then(function() { // Request success and no timeout console.log('good promise, no timeout! '); }) .catch(function(err) { // Error: response error, request timeout or runtime error console.log('promise error! ', err); });Wrapping this code in a function called fetchWithTimeout, whereby you pass in a timeout and fetch URL/settings would work well; since people like to use fetch in a variety of ways, I've chosen not to create a generalized function and instead am just providing the basic logic.
将这段代码包装在一个名为fetchWithTimeout的函数中,您可以传入一个超时值,然后获取URL /设置会很好地工作。 由于人们喜欢以多种方式使用访存,因此我选择不创建通用函数,而只是提供基本逻辑。
Many would argue that the timeout should come from the server but we all know us front-end devs don't always have control over both sides of a request. If you're looking for a fetch request timeout snippet, here you go!
许多人认为超时应该来自服务器,但是我们都知道前端开发人员并不总是能够控制请求的两端。 如果您正在寻找提取请求超时代码段,请点击这里!
翻译自: https://davidwalsh.name/fetch-timeout
获取商户订单信息超时获取