美文网首页
fetch的timeout

fetch的timeout

作者: 碟枫 | 来源:发表于2018-01-30 14:34 被阅读39次

    实现方式
    一、github/fetch#20

    var p = Promise.race([
      fetch('/resource-that-may-take-a-while'),
      new Promise(function (resolve, reject) {
        setTimeout(() => reject(new Error('request timeout')), 5000)
      })
    ])
    p.then(response => console.log(response))
    p.catch(error => console.log(error))
    

    二、github/fetch#20

    var req = new Request(url, option);
    req.fetch().then((res) => {
      console.log(res.status);
    }).catch((err) => {
      console.error(err); // this will also happen in `abort()` request
    });
    
    // timeout a request
    setTimeout(function() {
      req.abort(); // reject the fetching process
    }, 1000);
    

    三、github/fetch#20

    const oldfetch = fetch;
    fetch = function(input, opts) {
        return new Promise((resolve, reject) => {
            setTimeout(reject, opts.deadline);
            oldfetch(input, opts).then(resolve, reject);
        });
    }
    

    相关文章

      网友评论

          本文标题:fetch的timeout

          本文链接:https://www.haomeiwen.com/subject/zvhczxtx.html