api - How to convert an asynchronous function into synchronous function using promise in Node.js? -
i have changed code async suggested still not able access value , getting error of cannot read property '0' of undefined.the task_id not accessible third function not created:
app.post('/api/add_task',function(req,res,error){ var sql = "insert `campus_ambassador`.`tasks` ( `task_type`, `task_name`, `details`, `social_media_handles`, `media`, `created_date`, `updated_date`) values ('offline', 'golfed', 'ssss', '#soccer', 'sdfsd', '2012-12-26 00:00:00', '2012-12-26 00:00:00');" var sql1 = "select task_id tasks task_name='golfed'"; var sql2 = "insert `campus_ambassador`.`task_level` (`task_id`, `level_id`, `updated_on`, `created_on`) values ("+"'"+res1[0].task_id+"'"+", '3', '2012-12-26 00:00:00', '2012-12-26 00:00:00')"; var res1='' async.waterfall([ function(callback){ db.select(sql,function(err){ console.log("made task"); callback(null); }) }, function(callback){ db.select(sql1,function(err,data){ res1 = data; console.log(res1); console.log(res1[0].task_id); console.log("got task id of created task") res.end(); callback(null,data); }) }, function(callback){ db.select(sql2,function(err){ console.log(res1[0].task_id) console.log("updated task level table") callback(null); }) } ], function(err,results){ console.log(json.stringify(results)); }) })
this depend on few things. version of node using , if lib db support promise.
turning callback promise
if db doesnt support promise default have yourself, this:
var dbselectpromise = function(db, sql) { return new promise(function(resolve, reject) { db.select(sql, function(err, data) { if (err) { reject(err) } else { resolve(data) } }) }) }
using promise
once have promise (either made it, or native db) can use this
dbselectpromise(db, sql) .then(function(fristresult) { return dbselectpromise(db, sql1) }) .then(function(secondresult) { return dbselectpromise(db, sql2) }) .then(function(thirdresult) { // , on... }) .catch(function(err) { // here can handle errors of them })
using async/await
if node version 7.6 or higher can better. frist change promise function:
var dbselectpromise(db, sql) = async function { return new promise(function(resolve, reject) { db.select(sql, function(err, data) { if (err) { reject(err) } else { resolve(data) } }) }) }
then can use sync code:
var fristresult = await dbselectpromise(db, sql) var secontresult = await dbselectpromise(db, sql1) var thirdresult = await dbselectpromise(db, sql2)
edit save result accross multiples "then" can save result in outer scope, so:
var frist, second, third dbselectpromise(db, sql) .then(function(fristresult) { frist = fristresult return dbselectpromise(db, sql1) }) .then(function(secondresult) { second = secondresult return dbselectpromise(db, sql2) }) .then(function(thirdresult) { third = thirdresult // , on... }) .catch(function(err) { // here can handle errors of them })
wiki
Comments
Post a Comment