SOURCE

// https://mp.weixin.qq.com/s/uiWdL3qrCC9cxVBI87wKhA

const url = 'https://jsonplaceholder.typicode.com/todos/1'

const xhr = new XMLHttpRequest()
xhr.addEventListener('load',function(e){
    console.log(3,this.response)
})

xhr.open('GET',url)
xhr.send()

setTimeout(function () {
    xhr.abort()
},50)  // 时间小了 响应中没有内容  时间大了 响应中有内容 但是开发者感觉是比较模糊的

const ac = new AbortController()
let {signal} = ac 

fetch(url,{signal})
    .then(res=>res.json())
    .then(json => console.log(23,json))
    .catch(err => {
        console.log(25,err)
    })






const path = `https://jsonplaceholder.typicode.com/todos/`

function request (id,signal) {
    return fetch(`${path}${id}`,{signal})
        .then(res=>res.json())
        .then(json => console.log(40, id,json))
        .catch(err=>{
            console.log(id,err,JSON.stringify(err))
        })
}

for(let i of  [1,2,3,4]){
    console.log(47,i)
    request(i,signal)
}



//实现一个可以主动取消的 Promise

function _promise (signal) {
    return new Promise ((resolve,reject) => {
        signal&&signal.throwIfAborted()
        setTimeout(() => {
            Math.random() > .5 ? resolve('ok') : reject('no')
        },1000)
        signal && signal.addEventListener('abort',() => {
            reject(signal)
        })
    })
}

_promise(signal).then(res=>{
    console.log(71,res)
},err=>{
    console.error(73,err , err.msg ? err.msg : '没有msg ')
})

// 这里控制着  两个fetch (一个普通 , 一个fetch 数组式请求) 一个promise 
setTimeout(function () {
    ac.abort({
        msg : '手动停止',
        type : 'user'
    })
},5000)






console 命令行工具 X clear

                    
>
console