简体   繁体   中英

What's wrong with this async function?

async lsEntered(){
  if(this.service.wd == '')
    {
      await basic((this.service.wd));
    }
    else
    {
      await basic(('/'+this.service.wd));
    }

    this.files = await JSON.parse(localStorage.getItem('FILENAMES'));

    var filesList = document.getElementById(this.trackLine.toString());
    var li;
    for (var i = 0; i < this.files.length; i++) {
    li = document.createElement('li');
    li.appendChild(document.createTextNode(this.files[i].name));
    filesList.appendChild(li);
  }

  localStorage.clear();

}

I want to wait until basic is finished and JSON.parse finishes before displaying the values in the DOM. I'm getting the values of the previous call every time which is tell me the async is no working. To be fair I don't have tons of TS experience.

Edit: This is basic I was hoping not to have to deal with it as it's a javascript function and fragily integrated into this app.

var basic = function (path) {
    var ACCESS_TOKEN = '';
    var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
    dbx.filesListFolder({ path: path })
        .then(function (response) {
        localStorage.setItem('FILENAMES',JSON.stringify(response.entries));
        console.log(response);
    })
        .catch(function (error) {
        console.error(error);
    });
    return false;
}
let myPromise = new Promise((resolve, reject) => {
  // Work you want to execute
  resolve("I am done");
});

myPromise.then((successMessage) => {
  // successMessage is whatever we passed in the resolve(...) function above.

  console.log("Yay! " + successMessage);
});

You can only await promises 1 and basic is not returning a promise. You need to do

return dbx.filesListfolder(...)...

Also consider what Bergi said in their comment .


1: Actually, you can await any value, but there is no point in await ing something that is not a promise. By not returning the promise from basic , lsEntered won't wait for the local storage to be set.

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