javascript - Nodejs 如何使用 Promise 进行迭代

标签 javascript node.js asynchronous

我正在尝试迭代 AD 用户数组并返回一些用户信息。 我已经找了几个小时或更长时间了,但还没有完全理解 activedirectory2 npm 包的异步性质。

我得到了我需要的部分结果,但是当迭代用户名列表时,我只将第一个结果打印到控制台。

getADUser.js:

var ActiveDirectory = require('activedirectory2');
var config = require('../../conf/conf-ad.json')
var fileTime = require('./w32FiletimeToEpoch')
var moment = require('moment')
// Find user, return all
var ad = new ActiveDirectory(config);



var getADUser = function (sAMAccountName, opts) {
    return new Promise(function (resolve, reject) {
        ad.findUser(opts, sAMAccountName, function (err, user) {
            if (err) {
                console.log('ERROR: ' + JSON.stringify(err));
                // return;
            }
            if (!user) {
                console.log('User: ' + sAMAccountName + ' not found.');
            } else {
                if (user.userAccountControl == 514) {
                    user.userAccountControl = 'Disabled'
                } else {
                    user.userAccountControl = 'Active'
                }
                if (user.pwdLastSet) {
                    user.pwdLastSet = `${moment(fileTime(user.pwdLastSet))} - ${moment(fileTime(user.pwdLastSet)).fromNow()}`
                }
                if (user.lastLogonTimestamp) {
                    user.lastLogonTimestamp = `${moment(fileTime(user.lastLogonTimestamp))} - ${moment(fileTime(user.lastLogonTimestamp)).fromNow()}`
                }
                if (user.lastLogon) {
                    user.lastLogon = `${moment(fileTime(user.lastLogon))} - ${moment(fileTime(user.lastLogon)).fromNow()}`
                }
                // return;
                // return user.promise();
                // console.log(user)
                // test.push(user)
                resolve(JSON.stringify(user));
            }
        });
    })
}

module.exports = getADUser

检查ADCompletions.js:

var checks = ['USERONE', 'USERTWO']

let opts = {
    attributes: ['sAMAccountName', 'userAccountControl']
};
let checkADCompletions = function (userList) {
    let data = []
    return new Promise(function (resolve, reject) {
        return new Promise(function (res, rej) {
            for (let i = 0; i < userList.length; i++) {
                getADUser(userList[i], opts)
                    .then(function (s) {
                        data.push(s)
                    }).then(function () {
                        resolve(data)
                    })
            }
        })
    })
}

checkADCompletions(checks).then(function (d) {
    console.log(d) \\ Only prints the first user details
})

最佳答案

您可以像这样使用Promise.all:

let checkADCompletions = function (userList) {
    var promises = userList.map(function (user) {
        return getADUser(user, opts);
    })

    return Promise.all(promises);
}

您基本上是在创建一系列 promise ,然后同时执行它们。

然后像这样使用它:

checkADCompletions(checks)
.then(function (responses) {
    console.log(responses); // this will be an array
})
.catch(function (err) {
    // if any of the promises fail, it will enter here.
    // err will be the value of the rejected promise
})

Promise.all will fail even if just one of the checked users fail 。因此,您需要很好地处理错误,即处理 ad.findUser任何可能结果:

var getADUser = function (sAMAccountName, opts) {
    return new Promise(function (resolve, reject) {
        ad.findUser(opts, sAMAccountName, function (err, user) {
            if (err || user == null) {
                console.log('ERROR: ' + JSON.stringify(err));
                reject(err);
            }
            if (user.userAccountControl == 514) {
                user.userAccountControl = 'Disabled'
            } else {
                user.userAccountControl = 'Active'
            }
            if (user.pwdLastSet) {
                user.pwdLastSet = `${moment(fileTime(user.pwdLastSet))} - ${moment(fileTime(user.pwdLastSet)).fromNow()}`
            }
            if (user.lastLogonTimestamp) {
                user.lastLogonTimestamp = `${moment(fileTime(user.lastLogonTimestamp))} - ${moment(fileTime(user.lastLogonTimestamp)).fromNow()}`
            }
            if (user.lastLogon) {
                user.lastLogon = `${moment(fileTime(user.lastLogon))} - ${moment(fileTime(user.lastLogon)).fromNow()}`
            }
            resolve(user);
        });
    })
}

关于javascript - Nodejs 如何使用 Promise 进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46842515/

相关文章:

javascript - 如何缩放 HTML5 Canvas 而不使其模糊?

javascript - Express Node 服务器与其显示 html 之间的通信

javascript - 在 WebWorker (NWJS) 中不能需要 Node 模块

php - 在 Php header 重定向后提供反馈

javascript - 操纵 Meteor 光标

javascript - 在 node.js 中捕获异常

c# - Task.Factory.FromAsync 相当于 HttpWebRequest 和请求流代码

Scala Future 和 TimeoutException : how to know the root cause?

c# - 异步/等待不同的线程 ID

javascript - 无法在 JavaScript 中检索 json 值