javascript - Setting global variable in callback -


tried simplify code show problem.

var rp = require('request-promise'); var ids = [];  runmyfunction(); runmyfunction();  function runmyfunction() {     var id = 5;     console.log("runmyfunc:  "+ids);     if (ids.indexof(id)==-1){        myfunction(id);     } }  function myfunction(id) {     var options = {         uri: 'someuri'         , headers: {             'user-agent': 'request-promise'         }         , json: true     };     rp(options)         .then(function (response) {             ids.push(5);             console.log("myfunc: "+ids);         })         .catch(function (err) {            console.log(err);         }); } 

basically have function runmyfunction, should execute myfunction if there not id 12345 in it. if run 10 times , 11th id 12345 returned, should stop running function. problem id never gets pushed in array if request succeeded.

similar problems had request being asynchronous. cause in code well?

//edit played around , edited code. current code logs console:

runmyfunc:   runmyfunc:   myfunc:5 myfunc:5,5 

so because asynchronus. ideas avoid that?

not sure think problem solved using .bind() maybe :

var rp = require('request-promise'); var ids = [];   function runmyfunction() {     if (ids.indexof(12345)==-1){    myfunction();    } }  function myfunction() {     var options = {     uri: 'someuri'     , headers: {         'user-agent': 'request-promise'     }     , json: true }; rp(options)     .then(function (response,mids) {         mids.push(response.data.id);     }.bind(ids))     .catch(function (err) {        console.log(err);     }); } 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -