javascript - Meteor: How do I wait on functions returning before returning from my Meteor.method? -


i have meteor.method creates image , writes css. have spinner displays until method returns. method returns before functions create images , css have finished doing thing.

how include callback wait until image , css has been written before returning meteor.method?

this method:

createimage: function(coords) {    console.log('1: createimage')     var source="myimage.png";    var im = gm.subclass({imagemagick: true});    im(source)     .crop()      .write('newimage.png', function(err){        if (err) return console.dir(arguments)         console.log('4: image has been written')      }) // end of write function    fs.appendfile(directory + 'css.import.less', css, function (err) {    if (err) throw err;    console.log('3: "data append" appended file!');  });    console.log('2: image , css written')   return true; }, 

i've numbered console logs in order displayed in. want console.log messages displayed in order written in.

so instead of this:

//start of method console.log('1: createimage') console.log('4: image has been written') console.log('3: "data append" appended file!'); console.log('2: image , css written') //end of method 

i expect this:

//start of method console.log('1: createimage') console.log('2: image has been written') console.log('3: "data append" appended file!'); console.log('4: image , css written') //end of method 

currently method returning before functions write image , css have returned. effect of spinner displaying split second instead of waiting till functions create image , css have returned means spinner should displaying longer.

there's thing called promises in js. http://www.html5rocks.com/en/tutorials/es6/promises/

i think may figure out. basics so:

somepromiseshim(function(next) {   console.log("first"); next(); }).then(function(data, next) {   console.log("second"); next(); }).then(function(data, next) {   console.log("third"); next(); }); 

you may ask why should use - helps doing async stuff syncish. lets add async functionality code above.

somepromiseshim(function(next) {   console.log("first");    settimeout(function() { next(); }, 1000); }).then(function(data, next) {   console.log("second fire after 1 second"); next(); }).then(function(data, next) {   console.log("third"); }); 

there simple implementation of promise did friend on here: https://gist.github.com/schniz/0f525060aa9bec0b8d69 might learn how use using demo.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -