Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use promises inside express app?

I am trying to use a promise inside of app.get function that will run a query which will run on a promise. but problem is the response doesn't wait for the promise and just respondes back.

any idea how the code should so a promise can live inside app.get in express app?

like image 242
samiq Avatar asked Nov 16 '13 15:11

samiq


People also ask

How do I use Promise Express?

I am using Promise with Express. router. post('/Registration', function(req, res) { var Promise = require('promise'); var errorsArr = []; function username() { console. log("1"); return new Promise(function(resolve, reject) { User.

How do I use promises in node JS?

A Promise in Node means an action which will either be completed or rejected. In case of completion, the promise is kept and otherwise, the promise is broken. So as the word suggests either the promise is kept or it is broken. And unlike callbacks, promises can be chained.

How do you use nested promises?

Nested Promise: In a promise nesting when you return a promise inside a then method, and if the returned promise is already resolved/rejected, it will immediately call the subsequent then/catch method, if not it will wait. If promised is not return, it will execute parallelly.

Can we use Promise Inside Promise?

Here we need to first declare a Promise by using the Promise syntax, and we will be using the then() method for its execution and then inside that then() method we will create another promise by using the same Promise syntax as illustrated above, and then we will call our result of first inside that new Promise.


1 Answers

app.get('/test', function (req, res) {
    db.getData()
    .then(function (data) {
        res.setHeader('Content-Type', 'text/plain');
        res.end(data);
    })
    .catch(function (e) {
        res.status(500, {
            error: e
        });
    });
});
like image 142
Esailija Avatar answered Oct 09 '22 08:10

Esailija