0

I'm trying to return value of pagenumber from inner function to another. But due to asynchronous nature of javascript. I'm unable to do it as outer function gets executed earlier as compared to inner one. I'm trying to use callback to it but it will produce error if i call outer function(from somewhere else) without callback. My code is,

'GrabNewResponse':function(credentials,width){
  let pagenumber=0;
  app.request.get(url,function(data){
    let result=JSON.parse(data);
    pagenumber=result.data.pagenumber;
    if(result.success===true){
    app.dialog.close();
   }

  });
  return pagenumber;
}, 
CDJB
  • 14,043
  • 5
  • 29
  • 55
Gagan Singh
  • 200
  • 1
  • 13
  • "but it will produce error" So fix all the places it is used? – epascarello Feb 13 '20 at 17:02
  • Look into "async" functions (using the async keyword), and "await" your inner function. Also, RxJS pipe would do the trick. – Tim Consolazio Feb 13 '20 at 17:03
  • https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – epascarello Feb 13 '20 at 17:03
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Run_Script Feb 13 '20 at 17:04

1 Answers1

1

Asynchronous operations in Javascript cannot be effectively handled without callbacks, promises or the async/await keywords.

const request = () => new Promise((resolve, reject) => 
    app.request.get(url, (response) => response.success                                           
                                       ? resolve(response) 
                                       : reject(response)))

const o = {
    async GrabNewResponse(credentials, width) {
        const response = JSON.parse(await request(url))
        const { data: { pagenumber = 0 } } = response
        app.dialog.close()
        return pagenumber
    }
}
Ben Aston
  • 53,718
  • 65
  • 205
  • 331