简体   繁体   中英

How to return value from inner function to outer function

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;
}, 

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM