如何绑定表达路由返回Promise的一些功能?

时间:2021-08-04 19:55:11

How do I bind a function returning a promise to an express route?

如何绑定将承诺返回到快速路线的函数?

I have a function that works with my model objects which returns promises and I need to add it to controller function which react on a particular express route:

我有一个函数可以使用我的模型对象返回promises,我需要将它添加到控制器函数,该函数对特定的快速路由做出反应:

app.get('/students/list', controllerFunction);

(I have function findAllActiveStudents which read from file/database and returns promise). How to write controllerFunction which inside call findAllActiveStudents and returns result ?

(我有函数findAllActiveStudents从文件/数据库读取并返回promise)。如何编写调用findAllActiveStudents并返回结果的controllerFunction?

// inside controller file
exports controllerFunction = function(req, res) {

     // Here what to do

}

1 个解决方案

#1


2  

It can possibly be used like this:

它可以像这样使用:

// inside controller file
exports controllerFunction = function(req, res) {

    var promise = findAllActiveStudents(req);

    promise.then(function(result) {
        // format and send the result
        res.send(result);
    }, function(err) {
        // format and send the error
        res.send(error);
    });
}

#1


2  

It can possibly be used like this:

它可以像这样使用:

// inside controller file
exports controllerFunction = function(req, res) {

    var promise = findAllActiveStudents(req);

    promise.then(function(result) {
        // format and send the result
        res.send(result);
    }, function(err) {
        // format and send the error
        res.send(error);
    });
}