美文网首页
Promise并行执行

Promise并行执行

作者: 湘兰沅芷 | 来源:发表于2021-10-31 17:56 被阅读0次

    Promise.all() 等待所有任务结束

    function ajax (url) {
      return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest()
        xhr.open('GET', url)
        xhr.responseType = 'json'
        // readystate = 4
        xhr.onload = function () {
          if (this.status === 200) {
            resolve(this.response)
          } else {
            reject(this.statusText)
          }
        }
        xhr.send()
      })
    }
    
    var promise = Promise.all([
      ajax('/api/users.json'),
      ajax('/api/posts.json')
    ])
    promise.then(function(value) {
      console.log(value)
    }).catch(function(error) {
      console.log(error)
    })
    
    ajax('/api/urls.json')
      .then(value => {
        const urls = Object.values(value)
        const tasks = urls.map(url => ajax(url))
        return Promise.all(tasks)
      })
      .then(values => {
        console.log(values)
      })
    

    Promise.race() 只会等待第一个结束的任务
    举例请求超时的处理方式

    const request = ajax('/api/posts.json')
    const timeout = new Promise((resolve, reject) => {
      setTimeout(() => reject(new Error('timeout')), 500)
    })
    
    Promise.race([
      request,
      timeout
    ]).then(value => {
      console.log(value)
    })
    

    相关文章

      网友评论

          本文标题:Promise并行执行

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