在Node.js 6.11.0中处理异步函数

在ad.getUsersForGroup(...)下面的函数中,是一个异步函数。在其回调中,我使用teamId,该函数最终使用最后一个teamId。我认为这是因为到函数运行并输入回调时,所有的问题才完成。如何在回调中获取正确的teamId。我在console.logged中找到了问题所在。

 function getUsersFromAdTeams(adDictionary) {
    return new Promise((resolve, reject) => {
        try {
            var opts = {
                attributes: ['name', 'mail', 'thumbnailPhoto', 'title', 'uid', 'sAMAccountName', 'displayName']
            }
            let promises = [];

            for (teamId in adDictionary) {
                // console.log(teamId)
                let team = adDictionary[teamId];
                if(Object.keys(team.subteam).length > 0){
                    let subteams = team.subteam;
                    for (subteamId in subteams) {
                        let subteam = subteams[subteamId]

                        ad.getUsersForGroup(opts, subteam.AdName, function(err, users) {
                            if(err) {
                                console.log(err)
                            }
                            users.map(user => {
                                englishJobTitle = user.title.split('|')[1];
                                hasImage = Buffer.isBuffer(user.thumbnailPhoto);
                                subteam.users.members[user.uid] = {
                                    name: user.name,
                                    mail: user.mail,
                                    jobTitle: englishJobTitle,
                                    hasImage: hasImage
                                }
                            })
                            console.log(teamId); //prints last teamId multiple times
                        })
                        console.log(teamId);
                    }
                }

        }
        catch(err) {
            reject(err)
        }
    })
}
评论