I am using async waterfall to process nested condition in request, and using express framework. But I am confused how to process data to the next function in waterfall while the data is <promise>
. This promise data is a query from sequalize.
Here is the sketch
exports.getanythinghere = async function() {
var query = "SELECT anything, here "
"FROM anywhere WHERE ignore this query";
return new Promise((resolve, reject) => {
db.sequelize.query(query , {
type: QueryTypes.SELECT
}).then(wth => {
resolve(wth);
})
});
}
async.waterfall([
function(callback) {
const trying = getanythinghere ();
callback(null, trying);
},
function(dataone, callbackt) {
console.log("dataone is ", dataone);
}
], function(err, res) {
if (err) return callback(err);
callback(null, res);
});//waterfall
There dataone
is always dataone is Promise { <pending> }
What I am missing here. In jquery
, I will do getanythinghere().done(function(){});
But I want to have it in this callback of waterfall.
I used to do this few years ago, but I forgot since too much with java and php
Any help please..
CodePudding user response:
You don't need libraries like Async anymore, mainly because Javascript now supports async/await natively.
First, this is a Promise, because you can add it .then()
:
db.sequelize.query(query , {type: QueryTypes.SELECT});
Since it is a Promise, you don't need to (and shouldn't) wrap it inside another Promise, and also you can simply await it, instead of using .then()
const trying = await db.sequelize.query(query , {type: QueryTypes.SELECT});
Using await
or .then()
resolves the promise, and you get a value, instead of Promise { <pending> }
.
Then, you can directly use trying
, you don't need to pass it to another function like a waterfall.
console.log("trying is ", trying);
Finally, all your code holds in four lines :
try{
const query = `SELECT anything, here FROM anywhere WHERE ignore this query`;
const trying = await db.sequelize.query(query , {type: QueryTypes.SELECT});
console.log("trying is ", trying);
} catch(err) {
console.log(err);
}