promise 循环ajax,依次执行,同步

2017-10-17  本文已影响374人  yzc123446
var arr=[1,2,3,4,5,6,7,8,9]

  function PromiseForEach(arr, cb) {
    let realResult = []
    let result = Promise.resolve()
    arr.forEach((a, index) => {
      result = result.then(() => {
        return cb(a).then((res) => {
          realResult.push(res)
        })
      })
    })

    return result.then(() => {
      return realResult
    })
  }

  PromiseForEach(arr, (ele) => {

    return new Promise((resolve, reject) => {
          setTimeout(() => {
            console.log(ele);
            return resolve(ele);
          }, Math.random()*1000);
    })

  }).then((data) => {
    console.log("成功");
    console.log(data);
  }).catch((err) => {
    console.log("失败");
    console.log(err)
  });
上一篇下一篇

猜你喜欢

热点阅读