NodeJS 同步调用(等待和验证)

eqfvzcg8  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(114)

如何进行异步调用?我试着用这个代码:

abc = await ad.authenticate(username, password, function(err, auth) {
          if(err){
            console.log('ERROR: '+JSON.stringify(err));
            fail_found = err.name;
            return;
          }

          if(auth){
            console.log('Authenticated!');
          }else{
            console.log('Authenticated Faliled');
            fail_found = 'No Authenticated ';
          }          
        });
      }
      console.log("Fails?: ",fail_found);

NPM:https://www.npmjs.com/package/activedirectory2 Github:https://github.com/jsumners/node-activedirectory/
谢谢!

ny6fqffe

ny6fqffe1#

你可以尝试使用Promise

let myPromise = new Promise((resolve, reject) => {
     ad.authenticate(username, password, function(err, auth) {
      if(err){
        console.log('ERROR: '+JSON.stringify(err));
        fail_found = err.name;
        reject(fail_found)
        return;
      }

      if(auth){
        console.log('Authenticated!');
        resolve('Authenticated!');
      }else{
        console.log('Authenticated Faliled');
        fail_found = 'No Authenticated ';
        reject(fail_found)
      }          
    });
  }
  console.log("Fails?: ",fail_found);
  reject(fail_found)
});

myPromise.then((successMessage) => {
 console.log(successMessage);
}).catch(err => console.log(err))

或者在文档的第一部分显示一个promiseWrapper

const AD = require('activedirectory2').promiseWrapper;
const config = { url: 'ldap://dc.domain.com',
           baseDN: 'dc=domain,dc=com',
           username: '[email protected]',
           password: 'password' }
const ad = new AD(config);

相关问题