1

I have a promise set like that

async filterProject(Valuetofilter, uid) {
        var params = [this.db_name, parseInt(uid), this.password, 'project.project', 'search', [[['name', 'like', Valuetofilter]]]];
        var client = xmlrpc.createClient({ host: this.host, port:this.port, path: '/xmlrpc/2/object' })
        return new Promise((resolve, reject) => {
            client.methodCall('execute_kw', params, function(err, data) {
                if (err) {
                    reject(err)
                }
                else {
                    resolve(data)
                }
            })
        })
        
        
    }

then I call it like this

sd = new OdoooRpc('localhost', '8089', 'test', 'test', 'test');
var test = ''
var asdd = sd.authenticate().then(
    (uid) => {
        sd.filterProject('BF', uid)
        .then((ids) => {
            //console.log(ids)
            sd.readProjects(ids, uid)
            .then((records) =>{
                test = records
                //console.log(records)
            })
        }
        )
    }
);
console.log(asdd, test)

The problem is that test never gets updated as console log return

I really need to valorize the global variable, I have been searching this issue on stackoverflow for the past 2 days but I didnt find any solution. Is a promise the best approach here?

strangethingspy
  • 246
  • 1
  • 2
  • 13
  • 3
    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) – ASDFGerte Sep 08 '20 at 14:36
  • TL;DR you can't reliably do that. You will have to call .then every place you want use that value, you can't "unwrap" a Promise because the value may not be there yet, which is why your console.log fails. If you uncomment the console.log in your .then callback you'll see that the one at the bottom logs *before* that one. – Jared Smith Sep 08 '20 at 14:39
  • You absolutely can set the global variable to the value, and you're in fact doing just that. The problem with your code is that you're setting `test` to the value *after* you're calling `console.log(asdd, test)`. Say you added a button that logs `test` and only clicked it a few seconds after your page has loaded: it would print the `records` value perfectly fine. So the best approach to this issue depends mostly on how exactly you're planning to use the loaded value. –  Sep 08 '20 at 14:44
  • @ChrisG I need to get the data in order to update my vue app – strangethingspy Sep 08 '20 at 15:09
  • @JaredSmith I really need the value so I can pass it to vue – strangethingspy Sep 08 '20 at 15:12
  • @strangethingspy https://stackoverflow.com/questions/49745497/how-to-display-async-data-in-vue-template – Jared Smith Sep 08 '20 at 15:14
  • Why not load the data inside your Vue app and put it directly in its state? –  Sep 08 '20 at 17:08

0 Answers0