javascript - How to use yield with my own functions? -


i new generator concept. understanding if function returns promise, can used yield. have small node.js script looks this:

q.fcall(function*(){   var url = "mongodb://" + config.host + ":" + config.port + "/" + config.db;   var db = yield mongoclient.connect( url );   var data = yield makerequest();   console.log( data );   db.close(); });   function makerequest(){   var deferred = q.defer();   request({       "method" : "get",       "url" : "....",       "headers" : {           "accept" : "application/json",           "user_key" : "...."       }   },function(err,data){       if( err ){           deferred.reject( err );       }else{           deferred.resolve( data );       }   });   return deferred.promise; }   

i know works because porting callback hell style generator style. however, not see data in console.log.

what need change make work?

q.fcall not suited work generator functions. need use dedicated generator methods that, in case q.spawn:

q.spawn(function*() {   var url = "mongodb://" + config.host + ":" + config.port + "/" + config.db;   var db = yield mongoclient.connect( url );   try {     var data = yield makerequest();     console.log( data );   } {     db.close();   } }); 

without runner, generator won't automatically advanced asynchronously.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -