node.js - Promises not running in correct order -
the following logging in order: here1 here2 here5 here3 here4. although, here5 should last , it's not getting here6 @ all. how can here1 here6 run in order? using sailsjs , bluebird.
//manually wrapping callback api kaiseki function createkaisekiobject(classname, job) { console.log('here2'); return new promise(function(resolve, reject) { kaiseki.createobject(classname, job, function(err, res, body, success) { //resolve or reject promise if (err) { reject(err); return; } console.log('here3'); resolve(body); }); }); } function savejob(body) { console.log('here4', body); return jobs.create({ owner: req.user.id, jobid: body.objectid }); } function sendresponse(req, res) { console.log('here5'); return function(savedjob) { console.log('here6', savedjob, req, res); // res.json({ // success: true, // message: "running analysis on game", // jobid: savedjob.jobid // }); //return job return savedjob; }; } module.exports.index = function(req, res) { console.log('here1'); var jobid = uuid.v4(); var job = { owner: req.user.id, numofgames: 1, numofgamescompleted: 0 }; var classname = 'jobs'; //promise var createjob = createkaisekiobject(classname, job) .then(savejob) .then(sendresponse(req, res)); //when first step done, more stuff... createjob.then(function(savedjob) { //do more stuff here... console.log('here6'); }); };
first of don't believe jobs.create returns promise need wrap in 1 if want continue chaining.
function savejob(body) { console.log('here4', body); return function(body) { return new promise(function(resolve, reject) { jobs.create({ owner: req.user.id, jobid: body.objectid }).exec(function(err, job) { resolve(job); }); }); }; }
next make sure function returned sendresponse returns promise since returned function executed in chained block.
function sendresponse(req, res) { console.log('here5'); return function(savedjob) { return new promise(function(resolve, reject) { console.log('here6', savedjob, req, res); res.json({ success: true, message: "running analysis on game", jobid: savedjob.jobid }); //return job resolve(savedjob); }); }; }
Comments
Post a Comment