iterator - Need further help in making javascript sync generator handle async functions -


i relative newbie in node js. have requirement synchronously call async function (http request()). this article kylie simpson has helped me lot; code bit needed:

function request(url) {     // we're hiding asynchronicity,     // away main code of our generator     // `it.next(..)` generator's iterator-resume     // call     makeajaxcall( url, function(response){         it.next( response );     } );     // note: nothing returned here! }  function *main() {     var result1 = yield request( "http://some.url.1" );     var data = json.parse( result1 );      var result2 = yield request( "http://some.url.2?id=" + data.id );     var resp = json.parse( result2 );     console.log( "the value asked for: " + resp.value ); }  var = main(); it.next(); // started 

but need take 1 step further: need able pass result1 function (processresult() in example below), call request() if conditions met. this:

function request(url) {     makeajaxcall( url, function(response){         it.next( response );     } ); }  function processresult(resset) {     if (resset.length>100)         return request("http://some.url.1/offset100");     else         write2file(resset); }  function *main() {     var result1 = yield request( "http://some.url.1" );     processresult(result1) }  var = main(); it.next(); 

but when attempt this, request("http://some.url.1/offset100") not return values. ideas?

but when attempt this, request("http://some.url.1/offset100") not return values.

a generator function executes synchronously other function except when pausing using yield.

your call function processresult(resset){} synchronous call returns function *main() {} before async function request(url) {} has completed. in stead need keep yielding out call async function request(url){} inside generator function. can restructuring code way:

function processresult(resset) {     if (resset.length>100)         return true;     else         write2file(resset); // assuming function synchronous         return false; // not necessary function in case returns `undefined` default coerces false - illustrates point }  function *main() {     var result1 = yield request( "http://some.url.1" );     if(processresult(result1)) {         var offset100 = yield request("http://some.url.1/offset100");     }      // offset100  var = main(); it.next(); 

Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -