The async-await status is resolved, however the ajax request is still pending

Currently, I am attempting to handle a getJson call and process the data received. Despite trying various solutions such as using $.ajax's async: false (which did not work due to the query being cross domain), callbacks, and the .done portion of a basic $.ajax call, I have now turned to async-await. Below is an excerpt from my code:

var ths = getTrailheads(turl);
console.log("trailheads promise");
console.log(ths);
ths.then(function(data) {
  addTrailheadsToMap(data);
});

async function getTrailheads(turl) {
  var result = await $.ajax({
    url: turl,
    datatype: 'json'
  });

  return result;
}

Although it occasionally works when the AJAX call returns quickly enough, most of the time the console log displays:

https://i.sstatic.net/O5iA3.png

This screenshot portrays the promise with status marked as Resolved. The promise object exists, yet the status indicates Processing.

Despite this being a common issue, the typical solutions do not seem to be effective in my case. Any guidance would be greatly appreciated.

Update:

  preGetTrailheads(turl);
}
async function preGetTrailheads(turl) {
  var ths = await getTrailheads(turl);
  console.log("trailheads promise");
  console.log(ths);
  addTrailheadsToMap(ths);

}
async function getTrailheads(turl) {
  var result = await $.ajax({
    url: turl,
    datatype: 'json'
  });

  return result;
}

Now, instead of receiving a promise, I obtain the object directly; however, the object remains in a "Processing" state and fails upon usage. object dump

Update 2: I acknowledge that both of your approaches are correct, and that's the standard procedure. You can find my codepen here. It tends to function well, except for the initial run where it fails (also, successful output goes to the browser log). I need to investigate why this occurs in my application. Interestingly, reloading the page seems to make it work for a particular dataset.

Answer №1

Proper usage of async/await is demonstrated within the function getTrailheads, however, the code that calls it must also utilize async/await or handle promises accordingly. Assuming the calling code can be made async, simply adding await before the function call should suffice:

var ths = await getTrailheads(turl);

It's important to note that async/await essentially functions as syntactic sugar on top of promises, which is why not awaiting the result of getTrailheads will return a promise. Alternatively, you could opt to use

getTrailheads(turl).then(ths => {...})
if that aligns better with your overall structure.

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

The Vuetify expansion panel seems to be failing to reflect changes in the data

I've implemented pagination to display 5 expansion panels at a time from a list of over 60 items. However, I'm encountering an issue where the expansion panels are not updating correctly with the new lists. I am aware that a new list is being ret ...

Creating a unique-looking visual representation of progress with arcs

Looking to create a circular progress bar (see image below), with loading starting from the left bottom side up to the right bottom side. The empty state should be light-blue (#E8F6FD) and the progress color strong blue (#1CADEB). https://i.sstatic.net/VZ ...

CakePHP 2.0 fails to provide a 403 error code

When transitioning from cakePHP 1.3 to CakePHP 2.0, I encountered an issue with restricted actions not returning a 403 error when called by AJAX and the user is not logged in. In my previous setup, this served as an alert to prompt users to log back in. ...

Loading a basic content snippet dynamically within a view

After following this tutorial, I successfully created a simple functionality: clicking on a button to load content stored in a partial. My intention is to utilize this technique in various scenarios where I want to maintain lightweight views without clutte ...

Refresh the DIV by populating it with data retrieved from an AJAX call

My inquiry is regarding two divs: one containing an @ajax.beginform and the other being empty but hidden. I am trying to implement a scenario where the form in the first div makes an ajax request, and the action method of the controller checks if the model ...

Utilizing Ionic to implement a conditional statement for comparing a string with information retrieved from an Observable source

I have a piece of code where I fetch data about a country as an observable. I then attempt to compare my string this.city with the this.capital that I got from the Observable. If they are not the same, I want to show a new paragraph in the HTML by changi ...

Inconsistent performance of AJAX functionality

I've been diving deep into this problem for quite some time now. I have a feeling that someone with the right expertise will be able to pinpoint the issue, but for some reason, it's just not clicking for me. The basic functionality here revolves ...

What steps should be taken to handle files in the Next JS api?

My goal is to send a docx file to the browser for client preview. I've attempted two methods: const rs = fs.createReadStream(fullPath); res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.docume ...

Tips for maintaining the current object's status while utilizing ngFor in Angular

The JSON data provided is structured as follows. [ { "route":"vehicle", "next-route":"driver", "isActive":false }, { "title":"Driver", "route":"driver ...

The TypeScript compilation failed for the Next.js module

Working on a project using Next.js with typescript. The dev server was running smoothly, and I could see frontend changes instantly. However, after modifying the next.config.js file and restarting the server (later reverting the changes), compilation issue ...

The use of a nested loop in jQuery to render elements using the appendPe function only displays

Trying to fetch data from a drinks API using an AJAX call and then looping through to display the ingredients on the page. However, only the last item in the loop is being displayed when appending the results with jQuery. I am aware of some null values and ...

Using jQuery cookies to dynamically change the body id during page loading

Is it possible to dynamically change the body ID during page load? I recently created an application that successfully changes the body ID. Now, I'm interested in detecting the body ID that I have already selected during page loading. Below is the c ...

Is there an issue with invoking Spring controller methods from JavaScript (via ajax) that is causing them

Using JavaScript to send a request to a method in Spring controller, the code looks like this: <script language="javascript" type="text/javascript"> var xmlHttp function show() { if(typeof XMLHttpReques ...

Step-by-step guide on implementing a see-more/read-more feature using only anchors in the HTML

I am currently developing a website that will be managed by individuals who are not very tech-savvy. I want to empower them with the ability to add "see-more" anchors that utilize jQuery slide up/down functionality to reveal content. While my code works w ...

Guide on selecting every input field located within a table

My form is embedded within a table <form id="form"> <input type="submit" value="send" class="btn btn-w-m btn-primary" style="float: left;">Add transaction</input> <table class="table table-strip ...

What is the most effective method for retrieving Key-Value Pairs from a disorganized String?

Avoiding hard-coded rules specific to certain patterns is crucial. I am currently working on a project similar to AWS Textract (link here). I have successfully extracted data from files, albeit in an unstructured manner. Now, my goal is to find the best w ...

When incorporating script tags in React, an "Unexpected token" error may arise

I am in the process of converting my website to a React site, but I am encountering an issue with the script tags not working. It keeps showing an unexpected token error. Here is the code snippet: <div className="people"> How many people are you ...

Instructions for positioning a 3d cube within another 3d cube with the help of three.js

I'm currently working on a project involving cargo management and I am looking to create a 3D image of the packing order. I am new to using THREE.js and need assistance in rendering the objects inside the container. While I have the positions (x, y, ...

Generate a dynamic text-box and drop-down list using HTML and JavaScript

My current project involves generating dynamic text-boxes based on the selection from a drop-down list and input field. https://i.sstatic.net/CMtW9.png When a user chooses 'Option 1' from the drop-down list and enters input such as 'grass& ...

Is it possible to invoke an AngularJs service by clicking a button?

Recently, I've been working on some AngularJS code involving a service and controller. angular.module('myModule', []).service("AttendanceService", function ($http) { this.getdata = function () { return $http({ ...