Promise实现一个函数,通过fetch请求一个接口'/api/getdata'(可能成功,也可能失败),超过3秒钟请求未返回则认为超时

// 实现一个函数,通过fetch请求一个接口'/api/getdata'(可能成功,也可能失败),超过3秒钟请求未返回则认为超时,要求:使用console.log()打印‘成功’,‘失败’,‘超时’3种结果中的一种

// 1,不管3秒后请求返回的成功还是失败,均只打印超时

// 2. 3秒内请求返回成功(或者失败)只打印‘成功’(或失败),不打印超时

let functionTime = (time) => {
  return new Promise((resolve, reject)=> {
    setTimeout(() => {
      reject('请求超时')
    }, time);
  })
}
let fetchPromise = ()=>{
  return new Promise((resolve, reject) => {
    fetch(url).then(res=> {
      return res.json()
    }).then(res=> {
      resolve(res)
    }).catch(err=> {
      reject(err)
    })
  })
}
Promise.race([functionTime(3000), fetchPromise('/api/getData')]).then(res=> {
  console.log('成功----->', res)
}).catch(err=> {
  console.log('失败----->', err)
})

  

原文地址:https://www.cnblogs.com/soonK/p/15073829.html