Matthias
Matthias

Reputation: 495

NodeJS express, how te return a result of a function called with express post

i found some examples how to return values with await, but I have a function in my async function and found no solution how to pass the result from auth in ad.authenticate . Here is What I have:

async function authorize(username, password){
    ad.authenticate(username, password, function(err, auth){
        console.log("auth: " + auth);
    });
}

router.post('/ldapauth',function(req,res){
    var username = req.body.username;
    var password = req.body.password;
    authorize(username, password)
        .then(result => {
            console.log("result: " + result)
            res.status(200).send({
                result: result,
        });
    }).catch(err => {
        console.log(err);
    })
});

The result in the router.post is undefined, because I belive its called before the auth function had teh chance to return the auth value?

Console:
    result: undefined
    auth: true

Upvotes: 0

Views: 388

Answers (1)

slebetman
slebetman

Reputation: 113876

If you want to use .then() or await you will have to promisify the authorize function. While it's true that functions marked with the async keyword returns a promise it does not automatically promisify callbacks.

What you need to do is this:

function authorize(username, password){ // note: no async keyword
    return new Promise((resolve, reject) => {
        ad.authenticate(username, password, function(err, auth){
            if (err) {
                reject(err)
            }
            else {
                resolve(auth);
            }
        });
    });
}

The rest of your code is OK as is. Nothing else needs to be changed.

Upvotes: 1

Related Questions