JavaScript 忽略将对象添加到数组

function setUsersDefinitions(data, userID){

    let users = new Array();

    return new Promise((resolve)=>{

        data.forEach(el => {

            if (el.id_adder === userID) {

                getUserName(el.id_added).then(u => {

                    users.push({

                        username: u,

                        locked: el.locked !== null,

                        canUnlock: el.locked === userID,

                        id: el.id_added

                    })

                }).catch(e=>{

                    console.log(e);

                })

            } else {

                getUserName(el.id_adder).then(u=>{

                    users.push({

                        username: u,

                        locked: el.locked !== null,

                        canUnlock: el.locked === userID,

                        id: el.id_adder

                    })

                }).catch(e=>{

                    console.log(e);

                })

            }

        })

        resolve(users);

    })

}

问题是,当我尝试对生成的项目执行 console.log 时,它可以工作,但是当它调用 Array.push 方法时,它会忽略该命令。我究竟做错了什么?提前致谢。


呼啦一阵风
浏览 127回答 1
1回答

繁星淼淼

所有这些都应该使用 async/await 来完成,而不是将所有内容都包装在一个中Promise——这将极大地简化您的代码:async function setUsersDefinitions(data, userID){&nbsp; &nbsp; let users = new Array();&nbsp; &nbsp; for(var i=0;i<data.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; var el = data[i];&nbsp; &nbsp; &nbsp; &nbsp; var id = (el.id_adder === userID) ? el.id_added : el.id_adder;&nbsp; &nbsp; &nbsp; &nbsp; var u = await getUserName(id);&nbsp; &nbsp; &nbsp; &nbsp; users.push({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;username: u,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;locked: el.locked !== null,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;canUnlock: el.locked === userID,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;id: id&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; return users;}(注意:为简洁起见省略了错误处理)然后你应该await在任何地方调用这个函数(它本身必须在一个async函数中):async function doWork(){&nbsp; &nbsp; var users = await setUsersDefinitions(some_data, some_userID);&nbsp; &nbsp; console.log(users);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript