问题描述
es6中一个function内的循环,循环里有异步,怎么让最终的结果被return,在循环外return不是想要的结果
问题出现的环境背景及自己尝试过哪些方法
用vue2开发的web项目,Promise和async/await都有个问题就是循环内得到的是promise对象,无法在循环外return想要的结果
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
async _normalizeSongs(list) {
if(!list) {
return
}
let rest = []
let index = 1
console.log(list)
for(let i=0;i<list.length;i++) {
if(list[i].songid && list[i].albummid) {
let res = await getSongVkey(list[i].songmid)
if(res.code === ERR_OK) {
const filename = res.req_0.data.midurlinfo[0].filename
const vkey = res.req_0.data.midurlinfo[0].vkey
const newSong = createSong(list[i], filename, vkey)
// console.log(newSong)
rest.push(newSong)
}
}
index++
}
return rest
}
_genResult(data) {
let rest = []
if(data.zhida && data.zhida.singername) {
rest.push({...data.zhida,...{type: TYPE_SINGER}})
}
if(data.song) {
let promise = this._normalizeSongs(data.song.list)
promise.then((res) => {
console.log(res)
/* rest = rest.concat(res)
this.result = rest*/
rest = rest.concat(this._normalizeSongs(data.song.list))
})
}
console.log(rest)
return rest
}
你期待的结果是什么?实际看到的错误信息又是什么?
_genResult这个函数里promise里的res怎么return出这个函数,路过的道友们给看看,万分感谢
这个函数的第二个参数为回调函数(调用的时候写匿名函数就行了,手机回答没办法给你写代码)
这个回调函数的参数就是你要return的对象 。
调用大概是这样 gen(data,(res)=>{console.log(res)})
函数 在修改后面加个cb&&cb(rest)
-----补充
函数修改