【问题标题】:NodeJS express, how te return a result of a function called with express postNode JS express,如何返回用express post调用的函数的结果
【发布时间】:2020-12-16 00:05:42
【问题描述】:

我找到了一些如何使用 await 返回值的示例,但我的异步函数中有一个函数,但没有找到如何在 ad.authenticate 中传递 auth 的结果的解决方案强>。这是我所拥有的:

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);
    })
});

router.post 中的结果是未定义的,因为我相信它在 auth 函数有机会返回 auth 值之前被调用?

Console:
    result: undefined
    auth: true

【问题讨论】:

    标签: node.js express asynchronous async-await


    【解决方案1】:

    如果您想使用.then()await,您必须承诺授权功能。虽然用 async 关键字标记的函数确实会返回一个承诺,但它不会自动承诺回调。

    你需要做的是:

    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);
                }
            });
        });
    }
    

    您的代码的其余部分按原样正常。无需更改任何其他内容。

    【讨论】:

      猜你喜欢
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2021-12-24
      • 1970-01-01
      • 2019-08-08
      相关资源
      最近更新 更多