Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

利用reduce和Promise发送顺序队列请求。

imageimage
循环上面的数组进行数据请求,每次发送该数组中的一个元素(即第一次发送0的四个对象,成功后发送1的四个对象,以此类推,当发送完8后,停止));
问题是:应该发送9次就好了,现在发送了33次。不知道什么原因。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var datas = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12],
  [13]
]

// 模拟ajax请求
function upload (json) {
  return new Promise(resolve => {
    console.log('sendData: ', json)
    setTimeout(() => {
      resolve(json)
      console.log('receiveData: ', json)
    }, 2000)
  })
}

datas.reduce(async (prev, cur, i) => {
  let data = JSON.stringify(datas[i])
  await prev
  return upload(data) // this.$api.post封装成一个promise,前面一定要加return
}, Promise.resolve())

// sendData:  [1,2,3,4]
// 2s后
// receiveData:  [1,2,3,4]
// sendData:  [5,6,7,8]
// 4s后
// receiveData:  [5,6,7,8]
// sendData:  [9,10,11,12]
// 6s后
// receiveData:  [9,10,11,12]
// sendData:  [13]
// 8s后
// receiveData:  [13]

问题:

  1. this.$api.post封装成一个promise,前面一定要加return,不加return所有的请求一起都发出去了,就没有你说的前一个发送成功之后再发送后一个;
  2. result遍历了一遍,result[i]也是一个数组,你又reduce了一遍,你请求发送的是数组中每个元素的每个元素,一共8*4+1=33个请求。我觉得直接在result上应用reduce就行了,为什么要在每个子元素上应用reduce。

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...