美文网首页
2020-03-01 Promise.all

2020-03-01 Promise.all

作者: lessonSam | 来源:发表于2020-03-01 23:16 被阅读0次

先说一下 关于 promise.all 的应用场景,如果你的项目需要依赖两个异步操作结束操作之后,再往后进行,

可能你会这样

<script>
  // 请求二一:
  // let isResult1 = false
  // let isResult2 = false
  // $ajax({
  //   url: '',
  //   success: function () {
  //     console.log('结果1');
  //     isResult1 = true
  //     handleResult()
  //   }
  // })
  // // 请求二:
  // $ajax({
  //   url: '',
  //   success: function () {
  //     console.log('结果2');
  //     isResult2 = true
  //     handleResult()
  //   }
  // })
  //
  // function handleResult() {
  //   if (isResult1 && isResult2) {
  //     //
  //   }
  // }

Promise.all 的使用

  Promise.all([
      // new Promise((resolve, reject) => {
      //   $.ajax({
      //     url: 'url1',
      //     success: function (data) {
      //       resolve(data)
      //     }
      //   })
      // }),
      // new Promise((resolve, reject) => {
      //   $.ajax({
      //     url: 'url2',
      //     success: function (data) {
      //       resolve(data)
      //     }
      //   })
      // })

    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({name: 'why', age: 18})
      }, 2000)
    }),
    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({name: 'kobe', age: 19})
      }, 1000)
    })
  ]).then(results => {
    console.log(results);
  })
</script>

当然这里我只是利用 setTimeout 来模拟了一下
注意最后results 返回的是一个数组,而且是第一个请求的结果在前,后者在后可以通过result[0]类似的来查看

相关文章

网友评论

      本文标题:2020-03-01 Promise.all

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