How do I cancel an HTTP fetch() request?

前端 未结 6 1615
小蘑菇
小蘑菇 2020-11-22 14:58

There is a new API for making requests from JavaScript: fetch(). Is there any built in mechanism for canceling these requests in-flight?

6条回答
  •  太阳男子
    2020-11-22 15:33

    This works in browser and nodejs Live browser demo

    const cpFetch= require('cp-fetch');
    const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s';
     
    const chain = cpFetch(url, {timeout: 10000})
        .then(response => response.json())
        .then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))
     
    setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms 
    

提交回复
热议问题