JavaScript检查资源是否可以通过提取访问 [英] JavaScript checking if resource is reachable with fetch

查看:174
本文介绍了JavaScript检查资源是否可以通过提取访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上只是试图验证资源是否可以从正在执行的客户端访问。我不能使用 XHR ,因为目标资源不允许。



我很新JS和我目前正在使用(可执行文件):

  var done = false; 
var i = 1;
var t =https://i.stack.imgur.com/Ya15i.jpg; $!
$ b while(!done&& i< 4)
{
console.log(try+ i);

完成= chk(t);
sleep(1000);

i = i + 1;

if(done)
{
console.log(Reachable!);
休息;
}
else
{
console.log(Unreachable。);



函数chk(target)
{
console.log(checking+ target)
fetch(target, {mode:'no-cors'})。then(r => {
return true;
})
.catch(e => {
return false;
});
}

//忙碌假睡眠
函数sleep(s)
{
var now = new Date()。getTime();
while(new Date()。getTime()< now + s){/ * busy sleep * /}
}

我期待这段代码检查资源,打印结果,然后等待一秒。重复此操作直到3次尝试失败或者其中一次成功。

取而代之的是执行块,然后打印所有控制台。我知道 fetch / code>操作是异步的,但我想如果我以前声明 done 并实现它应该工作的睡眠。在最糟糕的情况下,while循环将使用先前声明的 done



如何实现所描述的行为?任何建议都是可以接受的。

你真的想要的是一个递归函数,在延迟 y 秒等检查url n 次数后返回一个promise。 。

类似于这个

 函数chk(target,times,延迟){
return new Promise((res,rej)=> {// return a promise

(function rec(i){//递归IIFE
fetch目标,{mode:'no-cors'})。then((r)=> {//获取资源
res(r); //解析promise如果成功
})。catch (err => {
if(times === 0)//如果尝试次数达到
return rej(err); //不要再次尝试

SE tTimeout(()=> rec( - 次),延迟)//否则,请等待并尝试
}); //再次尝试
})(times);

});
}

像这样使用

  var t =https://i.stack.imgur.com/Ya15i.jpg; 

chk(t,3,1000).then(image => {
console.log('success')
})。catch(err => {
console.log('error')
});

请注意,这不会在404或500上失败,任何响应都是成功的请求。 p>

I'm basically just trying to verify if a resource is reachable from the executing client. I can not use XHR, because the target resource doesn't allow that.

I'm pretty new to JS and am currently working with this ( executable here ):

    var done = false;
    var i = 1;
    var t = "https://i.stack.imgur.com/Ya15i.jpg";

    while(!done && i < 4)
    {
      console.log("try "+i);

      done = chk(t);
      sleep(1000);

      i = i+1;

      if (done)
      {
        console.log("Reachable!");
         break;
      }
      else
      {
         console.log("Unreachable.");
      }
    }

  function chk(target)
  {
    console.log("checking "+target)
    fetch(target, {mode: 'no-cors'}).then(r=>{
    return true;
    })
    .catch(e=>{
    return false;
    });
  }

  // busy fake sleep
  function sleep(s)
  {
      var now = new Date().getTime();
      while(new Date().getTime() < now + s){ /* busy sleep */ } 
  }

I was expecting this code to check for the resource, print the result, then wait for a sec. Repeat this until 3 tries were unsuccessful or one of them was successful.

Instead the execution blocks for a while, then prints all of the console.logs at once and the resource is never reachable (which it is).

I do know that the fetch operation is asynchronous, but I figured if I previously declare done and implement a sleep it should work. In the worst case, the while loop would use the previously declared done.

How do I achieve the described behavior? Any advice is welcome.

解决方案

Your sleep function is blocking, what you really want is a recursive function that returns a promise after checking the url n times with a delay of y seconds etc.

Something like this

function chk(target, times, delay) {
    return new Promise((res, rej) => {                       // return a promise

        (function rec(i) {                                   // recursive IIFE
            fetch(target, {mode: 'no-cors'}).then((r) => {   // fetch the resourse
                res(r);                                      // resolve promise if success
            }).catch( err => {
                if (times === 0)                             // if number of tries reached
                    return rej(err);                         // don't try again

                setTimeout(() => rec(--times), delay )       // otherwise, wait and try 
            });                                              // again until no more tries
        })(times);

    });
}

To be used like this

var t = "https://i.stack.imgur.com/Ya15i.jpg";

chk(t, 3, 1000).then( image => {
    console.log('success')
}).catch( err => {
    console.log('error')
});

And note that this does not fail on 404 or 500, any response is a successful request.

这篇关于JavaScript检查资源是否可以通过提取访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆