gpt4 book ai didi

javascript - map 的返回值未定义

转载 作者:行者123 更新时间:2023-12-03 01:36:39 25 4
gpt4 key购买 nike

我的数据看起来像这样:

[ 
{ ItemID: 1, Path: '/Admin', Name: 'Admin' },
{ ItemID: 2, Path: '/Product', Name: 'Product' },
{ ItemID: 3, Path: '/Reports', Name: 'Reports' }
]

问题是我无法让它返回正确的结果。它当前返回未定义。我有一种感觉,这可能与范围或函数的调用方式有关。

这是我到目前为止所拥有的:

const result = data
.map(curr => {

// Map over the object and check the names of the object
// create a new key `groupName` if matched

if (curr.Name == "Admin") {
let groupName = "Admin Access";
return { ...curr, groupName: groupName };
} else if (curr.Name == "Product") {
let groupName = "Product Access";
return { ...curr, groupName: groupName };
} else if (curr.Name == "Reports") {
let groupName = "Reports";
return { ...curr, groupName: groupName };
}
})
.map(obj => {
// obj now looks like this
//{ ItemID: 1, Path: '/Admin', Name: 'Admin', groupName: 'Admin Access' }
//{ ItemID: 2, Path: '/Product',Name: 'Product', groupName: 'Product Access'}
//{ ItemID: 3, Path: '/Reports',Name: 'Reports', groupName: 'Reports' }

// Map over the object and check permissions for access

let enabled = checkInGroup(username, obj.groupName)
.then(function(isMember) {
if (isMember) {
return obj; //isMember will return true or false
}
});
return obj == enabled; //if enabled then add to return object
});

console.log("===> result ", result);

预期结果是:(假设用户无法访问管理员)

[ 
{ ItemID: 2, Path: '/Product', Name: 'Product' },
{ ItemID: 1, Path: '/Reports', Name: 'Reports' }
]

编辑:添加 CheckInGroup 功能

function checkInGroup(username, groupName) {
return new Promise(function(resolve, reject) {
ad.isUserMemberOf(username, groupName, function(err, isMember) {
if (err) {
return res.json("Error ", err);
}
resolve(isMember);
});
});
}

最佳答案

.then() 始终返回一个 Promise,因此 obj ===enabled 将不起作用。您无法使异步代码同步。一旦有了异步函数,链上的每个调用者都需要能够处理它。

您可以获取 promise 列表并等待所有 promise 都得到解决,然后过滤掉无效的 promise :

const promises = data
.map(curr => {

// Map over the object and check the names of the object
// create a new key `groupName` if matched

if (curr.Name == "Admin") {
let groupName = "Admin Access";
return { ...curr, groupName: groupName };
} else if (curr.Name == "Product") {
let groupName = "Product Access";
return { ...curr, groupName: groupName };
} else if (curr.Name == "Reports") {
let groupName = "Reports";
return { ...curr, groupName: groupName };
}
})
.map(obj => {
// Map over the object and check permissions for access
return checkInGroup(username, obj.groupName)
.then(function(isMember) {
obj.enabled = isMember;
return obj;
});
});

Promise.all(promises).then(result => {
console.log(result.filter(obj => obj.enabled));
});

关于javascript - map 的返回值未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51042353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com