What is the issue with this asynchronous function?

async getListOfFiles(){
  if(this.service.wd == '') {
    await getBasic((this.service.wd));
  } else {
    await getBasic(('/'+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 am facing an issue where I need to wait for the 'getBasic' function and JSON parsing to finish before displaying the values on the DOM. Currently, I am getting values from the previous call every time, which indicates that the asynchronous process is not working as expected. As I do not have much TypeScript experience, it's challenging for me to debug this.

Edit: The 'getBasic' function is a JavaScript function integrated into this application quite delicately, and I was hoping to avoid dealing with it directly.

var getBasic = 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;
}

Answer №1

const myPromise = new Promise((resolve, reject) => {
  // Add your code here
  resolve("Task completed successfully");
});

myPromise.then((message) => {
  // The message is the one we passed in the resolve(...) function.

  console.log("Great news! " + message);
});

Answer №2

Waiting for promises is essential, and unfortunately basic does not return a promise. To address this issue, you should consider using

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

It's also worth noting the insights shared by Bergi in their comment.


1: Technically, you can use await on any value, but it's ineffective to await something that isn't a promise. If basic fails to return a promise, lsEntered won't wait for local storage to be properly set.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do Angular 2 component getters get reevaluated with each update?

What advantages do getters offer compared to attributes initialized using ngOnInit? ...

What is the best way to time a Google Cloud Function to execute at the exact second?

In my attempt to schedule a cloud function using the Pub/Sub trigger method along with crontabs, I realized that it only provides granularity to the nearest minute. However, for my specific application - which involves working with trades at precise time ...

Tips for effectively utilizing URLSearchParams in Angular 5 HttpClient's "get" function

When working with Angular 4.2, I used the Http service and made use of the get method by passing in a URLSearchParams object as the search parameter: this.http.get(url, {headers: this.setHeaders(), search: params}) Now I am looking to upgrade to Angular ...

How can I extract the text within an element based on the position of the

In my current project, I have incorporated the incredibly useful jQuery TextRange plugin. Within a highlight div positioned above a textarea element, it is crucial for me to identify the specific element that the user is currently editing. To better illust ...

Modify the color of the div element after an ajax function is executed

My original concept involves choosing dates from a calendar, sending those selected dates through ajax, and then displaying only the chosen dates on the calendar as holidays. I aim to highlight these selected dates in a different color by querying the data ...

Angular 2 router hybrid application: URL resets after navigation

Each time a route is changed, the correct component is rendered but there seems to be an issue with the path. For example, when navigating from /items to /add-item, the URL changes momentarily but then reverts back. This issue occurs on every page, reg ...

Different node types can utilize jsplumb to modify their edge paintstyles

Currently, I am utilizing jsPlumb within my Angular application to establish connections between various elements. In this scenario, I have three distinct node types: subservice, entryAssets, and exitAssets. My objective is to apply different connection st ...

Use vue.js to add a block of content after every sixth iteration in a loop

Currently, I have a list of offer cards rendering through a loop. I am adding a row div every 3rd column (bootstrap) element. Now, I need to also add another column element (banner block) for every 6th element in order to achieve a layout like the one show ...

Encountering this issue? Error TS2304: Name not found

When I attempt to run unit tests for my Angular application using 'ng test', I encounter the error message: "Error TS2304: Cannot find name.." Interestingly, running 'ng serve' works without any issues. I followed a guide (link provide ...

Please reset the form fields after the most recent edit

I've created a form that includes multiple select elements. When an option is selected, it activates the next select element and updates it with values using Ajax and PHP. However, I'm facing an issue where changing a previous option only resets ...

What is the reason for the failure of this code to store data in local storage (undefined)?

After creating a new div with data from an input form, I noticed that the first div properly saves the inputted data. However, when I try to input new data, the div displays an undefined value. first attempt second attempt 0: {name: "Milk", amount: "30"} ...

How can I capture the click event on the oktext in Ionic?

When using Ionic, I have a select button with options for okText and cancelText. The issue I am facing is that when I click on okText, the menu closes as expected due to this attribute. However, I am interested in implementing it through click events. Belo ...

Add a new division to a component when a specific event handler is triggered by another component using React and the reduce method

Currently, I am developing an interactive drag-and-drop application using React and Redux. My goal is to insert a new div element into a container when the ondragstart event handler is triggered by a component. The component responsible for the dragging o ...

Slider in Angular Material not moving along the track

When I attempt to slide the mat-slider control using the mouse, it doesn't move left or right. Instead, it only responds when I click on a specific point along the sliding line. Here is the code snippet I am using: <div> <mat-slider>& ...

Activate the Giphy search feature in the Slack Nestor bot's response

How can the nestor bot be configured to use a giphy search when replying in a Slack channel where the giphy plugin is active? Can something like msg.reply('/giphy ' + text, done); be used for this purpose? ...

Ways to activate a function onInit in Angular version 9

Currently, I have a function that is activated by clicking a button: export class ExhibitorDetailsComponent implements OnInit { @ViewChild(MapInfoWindow, { static: false }) infoWindow: MapInfoWindow openInfo(marker: MapMarker, content) { this.in ...

The changes made to $scope in AngularJS are not being displayed in the view

The View Section <div class="col-sm-8" data-ng-init="init_enable_disable()"> <select class="form-control" style="margin-top: 5px;" data-ng-model="schedule.scheduleType" data-ng-change="enable_disableDiv(schedule.scheduleType);"> ...

Issue encountered while attempting to differentiate 'object Object'. NgFor only permits arrays and iterables

Having a JSON file containing a list of properties for sale, I am attempting to utilize *NgFor to iterate through the data and generate a list. Being relatively new to Angular and app development, there's a possibility that I might have misunderstood ...

Animations of bezier curves created with Three.js

UPDATED: SOLUTION FOUND I am in need of guidance on how to create animation for the movement of points along a curve to simulate string motion in 3D while keeping performance in mind. Imagine multiple strings between two points, for example. Check out t ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...