javascript - JS - then and waiting for a promise -


a common topic know want confirm understanding on world of js , promises.

so have following segment of code failing in then block doesn't wait segment above finished. namely i'm not getting final/correct value of okcheck.

var okcheck = false;  user.findone({publicid: id}, function (err, userinfo) {       if ( userinfo.checked.indexof(id) > -1 ){         okcheck = true;       } }) .then(function() {       //do additional stuff using boolean okcheck } 

so fix - understand need use return - correct?

var okcheck = false;  user.findone({publicid: id}, function (err, userinfo) {       if ( userinfo.checked.indexof(id) > -1 ){         okcheck = true;       }       return okcheck; }) .then(function() {       //do additional stuff using boolean okcheck } 

is correct - namely guaranteed i'll have final value of okcheck?

thanks.

from understand need use return - correct?

yes. returning value doesn't influence timing-related.

the point value return then callback resolution value of promise returns, , become argument of next callback in chain.

you should not modify outer-scope variables asynchronous callbacks. right approach defer actions until promise has resolved, not "wait" variable value appear:

// no `var` here! user.findone({publicid: id}).then(function(userinfo) {     return userinfo.checked.indexof(id) > -1; //  ^^^^^^ return boolean }).then(function(okcheck) { //               ^^^^^^^ receive here parameter     … // additional stuff using }); 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -