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?
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.
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.
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.
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.
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
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With