Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

循环列表操作,如何获得最终的操作结果列表?

可能标题描述的不够明确,详细解释如下:
我有这样一个循环

var sizeList = []
imgs.forEach((item, index) => {
  request({
    url: item,
    encoding: null
  }, (err, res, body) => {
    let buffer = body
    sizeList.push(sizeOf(buffer))
    console.log(sizeList)
  })
})
console.log('全局', sizeList)

问题1:
console.log(sizeList)会逐渐打印出结果

[ { height: 202, width: 172, type: 'png' } ]
[ { height: 202, width: 172, type: 'png' },
  { height: 837, width: 750, type: 'png' } ]
[ { height: 202, width: 172, type: 'png' },
  { height: 837, width: 750, type: 'png' },
  { height: 837, width: 750, type: 'png' } ]

请问我如何直接获得最后的一次完整的数组结果,而不要逐次叠加循环的过程?
问题2:
console.log('全局', sizeList)目前得到的是空数组[]
如何使外部console.log('全局', sizeList)获取到循环的最终数组列表呢?


还望得到解答,谢谢!


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

1 Reply

0 votes
by (71.8m points)

request请求是异步 建议改为同步执行 在imgs.length-1 最后一次打印值
https://es6.ruanyifeng.com/#docs/async


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...