简体   繁体   English

JavaScript忽略将对象添加到数组

[英]JavaScript ignoring adding object to array

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);
    })
}

The problem is that when i try doing a console.log of the item generated it works but when it call Array.push method, it ignore that command.问题是,当我尝试执行生成的项目的 console.log 时,它可以工作,但是当它调用 Array.push 方法时,它会忽略该命令。 What am I doing wrong?我究竟做错了什么? Thanks in advance.提前致谢。

All of this should be done with async/await, and not by wrapping the whole lot in a Promise - it will hugely simplify your code:所有这一切都应该通过 async/await 来完成,而不是通过将所有内容包装在一个Promise ——它将极大地简化您的代码:

async function setUsersDefinitions(data, userID){
    let users = new Array();
    for(var i=0;i<data.length;i++){
        var el = data[i];
        var id = (el.id_adder === userID) ? el.id_added : el.id_adder;
        var u = await getUserName(id);
        users.push({
                     username: u,
                     locked: el.locked !== null,
                     canUnlock: el.locked === userID,
                     id: id
                  });
    }
    return users;
}

(Note: Error handling omitted for brevity) (注意:为简洁起见省略了错误处理)

You should then await this function wherever you call it (must itself be within an async function):然后你应该在你调用它的任何地方await这个函数(它本身必须在一个async函数中):

async function doWork(){
    var users = await setUsersDefinitions(some_data, some_userID);
    console.log(users);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM