How to ensure vanilla JavaScript ES6 waits for Ajax requests to be completed

I am currently in the process of developing a website that utilizes two APIs.

One issue I encountered is ensuring that my Google Maps initialization function waits for a response from one of the APIs before executing.

Here is a snippet of my code:

let Url = "https://ipinfo.io/json";
async function getInfo(url) {
  const response = await fetch(url);
  // console.log(response);
  const data = await response.json();
  return data;
}
let ipInfo = getInfo(Url);
console.log(ipInfo);

//Google maps
function initMap() {
  var place = {
    lat: -25.363,
    lng: 131.044
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: place
  });
  var marker = new google.maps.Marker({
    position: place,
    map: map
  });
}

My current challenge lies in synchronizing the execution of the initMap() function with the completion of the getInfo() function. I attempted to resolve this by implementing the following:

let ipInfo = getInfo(Url).then(function(){initMap()...Rest of code});

Unfortunately, this approach did not yield the desired result.

Answer №1

When using the async and await keywords, you can simplify your code like this:

let ipInfo = await getInfo(Url);
// continue with the rest of your code using ipInfo

If you prefer to stick with the Promise format, then your original approach should work as well:

getInfo(Url)
  .then(info => {
    initMap();
    // more code here
  });

Keep in mind that the Promise format won't return the value back to a variable.

If neither method is working for you, there may be a syntax error in your code.

Answer №2

Upon examining the asynchronous structure, it appears logical to consolidate all operations within a single function:

let APIurl = "https://ipinfo.io/json";

//Initializing Google maps asynchronously
async function displayMap(url) {
  const response = await fetch(url);
  const data = await response.json();
  var location = {
    lat: -25.363,
    lng: 131.044
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: location
  });
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });

  return map;
}

displayMap(APIurl).then(map => { /* Perform additional tasks here */ })

If there are issues with early execution, ensure that both awaited elements are indeed returning promises or leveraging async functions.

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

How can you dynamically change the value of a React datetime slider picker using code?

I can't figure out how to programmatically update the value of the React datetime slider picker, especially when I click on a button. The rendering code for the widget looks like this: <RDSPwidget enableSecond={true} /> This is how my ...

Please proceed with submitting your choices in the order that you have selected

My goal is to submit options from a dropdown list in the order they are selected, rather than in the order they appear in the list. How can I achieve this? Here is the HTML code for the dropdown: < select style = "padding: 1em;" name = "skills" multi ...

When working with Sequelize querying, the response is showing an error indicating a column that does

I am currently developing a small REST API in express.js using the ORM sequelize. Currently facing the following issue: I want to retrieve all customers along with their photos. I have two tables, Customer and CustomerPhoto, with a 1:1 relationship (meani ...

The issue of memory leakage caused by jQuery Ajax requests

A problem has arisen on my website where memory is being leaked in both IE8 and Firefox. The Windows Process Explorer shows a continuous growth in memory usage over time. The issue arises when the page requests the "unplanned.json" URL, which is a static ...

Converting Date Format According to Visitor's Time Zone in VueJs/JS

I have a Date in string Format: 2020-07-13 7:07 AM (which is indian time). I am looking to adjust this time according to the browser's time zone, which could be either in the US or Africa. I have attempted various methods to convert it accurately. He ...

Having trouble with router.push in Vue3 and Vuex4?

Encountering some issues with Vue 3 and Vuex. Attempting to redirect users when logged in within my Vuex file, but the redirection is not happening as expected. No errors are being returned, only a link change without actually redirecting to another page. ...

Smooth transitions between points in animations using the D3 easing function

I'm working on an animated line chart that displays data related to play activities. I've been experimenting with changing the animation style between data points on the chart using d3.ease Currently, my code looks like this: path .attr("stro ...

Encountering difficulty locating the $wpdb variable during an AJAX request

I am currently developing a PHP application for WordPress and facing a challenge in retrieving a value from a database using AJAX every 2 seconds. I have created a new function in a separate file to handle this task. <?php global $wpdb; function retrie ...

A step-by-step guide on displaying a loading spinner during the retrieval and assembly of a component framework (Astro Island) with Vue and AstroJS

Here is the astro code I'm working on: --- import BaseLayout from '../../layouts/BaseLayout.astro'; import ListadoProfesionales from "../../components/pages/ListadoProfesionales/ListadoProfesionales.vue"; --- <BaseLayout title= ...

Removing Embedded Json Element from a Collection in AngularJS HTML

In my JSON Collection, I want to display the Email ID that is marked as IsPreffered = TRUE using AngularJS HTML without using JavaScript. This is my JSON Collection: { "user" : [ { "Name" : "B. Balamanigandan", "Email": [ ...

Node.js encounters issues when attempting to rename a folder

I am facing an issue while attempting to rename a folder within a WordPress theme after performing search-replace operations using a node script. The renaming process for the folder seems to be unsuccessful. My objective is to change this public_html/wp- ...

Navigating a controller variable to access a property of a service

I've been struggling to access a property of a service through a bound controller variable in a template. Controller: app.controller('VictoryController', function($scope, AlertStatisticsService) { $scope.AlertStats = AlertStatisticsSer ...

How can I extract an array of objects from a response in Angular?

Arrange array of objects from the received data. Here is the data that I received. [ {name:someName, value:20}, {name:"", value:21} {name:someName, value:25} {name:someName , value:27} {name:"", value:21} {name:someName, value:20} ] I am looki ...

Toggle Form Section Visibility

I am working on a table with five rows that have upload buttons. Each time I submit a row, the page refreshes, but I want to hide all but one row at a time. When the first submit button is clicked, it should show the next row and hide the previous ones. Th ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

Updating Multiple Divs with AJAX and PHP

Hey there, everyone! I found this code snippet on a website and need some help with it. var xmlhttp function showCustomer(str,str2) { xmlhttp=GetXmlHttpObject(); if (xmlhttp==null) { alert ("It seems like your browser doesn't support AJAX. Pleas ...

No action detected following the import into Redux form

This is my very first project in React. After completing a training course on Udemy, I have reached the following code but am stuck trying to integrate the action into the container (Is Container correct?). Here is the code I have put together from variou ...

Prevent mobile users from entering text with Material UI Autocomplete on keyboard

Currently, I am utilizing the Material UI Autocomplete component for multi-select functionality. Although it functions perfectly on desktop, I want to prevent keyboard input on mobile devices and only allow touch selection. Essentially, I do not want the v ...

Mocha Test Runs Are Exceeding Time Limits

I've updated to Node.js 4.0 which now supports generators. After trying gulp-mocha-co and upgrading to Node 4.0 for generator support, I encountered timeouts in my mocha tests when trying to make them generator-friendly. Adding the * to my mocha unit ...

What is the best way to add a style to the currently active link on a NavLink component using the mui styled() function

I have a custom NavLink component that I want to style with an ".active" class when it is active. However, I am not sure how to achieve this using the "styled()" function in MUI. Does anyone know how to accomplish this? Below is the code for my custom Nav ...