A step-by-step guide on accessing an API to check the status updates of ongoing API calls

I'm facing an issue with making two API calls concurrently. The goal is to have call X executed first, while Y should run in parallel and keep calling itself recursively until the X API resolves. Both calls should be initiated immediately upon clicking a button.

function X () {
return new Promise((resolve,reject) => {
Service.requestAPI(RequestMethod.GET, API_URL.validateProductStatus)
      .then(response => {
resolve(response)
} 
}
}

function Y () {
Service.requestAPI(RequestMethod.GET, API_URL.validateProductStatus)
      .then(response => {
        if(response){
          setTimeout(() => {
            this.onStatusChange()
          },1000)
}
} 
}

async function buttonCLick() {
const XResponse = await X();
Y();
}

The current implementation is not working as expected. The second call, Y, is being treated as a synchronous call instead of asynchronous. What could be causing this issue?

Answer №1

When using the await keyword, it essentially pauses the execution of a function until an asynchronous call is completed. Your code snippet seems to be missing some crucial elements to offer a tailored solution for your specific scenario. Generally speaking, when you want to perform async processing while updating dynamic statuses, you will either need to utilize callbacks or work with streams.

let sleep = ms => new Promise(r => setTimeout(r, ms));

let doAsyncWork = async onProgress => {
  let n = 100;
  for (let i = 0; i < n; i++) {
    await sleep(Math.random() * 100);
    onProgress(i / n);
  }
  onProgress(1);
};

let updateProgress = progress => {
  document.querySelector('div').textContent = progress < 1 ? 
    `Working, ${progress * 100}%` :
    `Complete!`;
};

doAsyncWork(updateProgress);
<div></div>

Answer №2

await will pause the program's execution until X is resolved. One method to accomplish this is by using a shared variable that determines whether or not to execute Y:

let callY = true;

const x = () => {
  return new Promise((resolve, reject) => {
    // make an API call
    setTimeout(() => resolve("X has been resolved"), 3000);
  });
};

const y = () => {
  if (callY) {
    console.log("waiting for X");
    // make an API call
    // recursively call the function after resolving based on the response
    setTimeout(() => y(), 1000); // calling the function after 3 seconds
  }
};

async function buttonClick() {
  x().then(res => {
    console.log(res);
    callY = false;
  });
  
  y();
}

buttonClick();

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 issue with ng-if not functioning within ng-repeat is that the ng-if directive

My issue is with using ng-if inside an ng-repeat in AngularJS. Despite updating to the latest version on 09/27/2014, I am still unable to make it work properly. The code functions perfectly outside of ng-repeat, and also works fine inside ng-repeat when us ...

Issues within jQuery internal workings, implementing improved exception handling for fn.bind/fn.apply on draggable elements

I've been experimenting with wrapping JavaScript try/catch blocks as demonstrated on this link. It functions properly, essentially encapsulating code in a try/catch block to handle errors like so: $.handleErrors(function(e){ console.log("an erro ...

Guide on exporting a function from a module as a class property

How to export a function as a class property from a module? Even if modifiers such as public are added, when a class property points to a function within a module, it behaves as though it is private. There are multiple ways to define a property (a, b, c ...

Determining the file size of an HTML and JavaScript webpage using JavaScript

Is there a way to determine the amount of bytes downloaded by the browser on an HTML+JS+CSS page with a set size during page load? I am looking for this information in order to display a meaningful progress bar to the user, where the progress advances bas ...

React does not automatically re-render components created with the built-in function

I'm facing some confusion with the behavior in my code: I've created a component that should function as a menu using MaterialUI. The idea is that when a button in the menu is clicked, it becomes "active" and visually reflects this change by set ...

What is the best method to determine the currency associated with the code in dinero.js?

Is there an easy way to locate the dinero currency in the dinero.js/currencies package using its code? For example, a function called getCurrency that accepts a string as input and outputs the corresponding dinero currency. ...

Halt and anticipate a boolean reply from another function

Is there a way to create two functions in JavaScript, run one of them, then within that function, execute the other and pause until it receives a response (yes or no) before moving on to an if statement? The user's response should be manual. Here is ...

How can I change an icon and switch themes using onClick in react js?

I have successfully implemented an icon click feature to change the colorscheme of my website (in line 21 and changeTheme). However, I also want the icon to toggle between FaRegMoon and FaRegSun when clicked (switching from FaRegMoon to FaRegSun and vice v ...

Encountered a 'Topology is closed' error while using EJS

After creating my profile.ejs page, I encountered an error upon reloading the page. Can someone help me understand what's causing this issue? Below is all the code I've used. My setup includes Node.js and Express as the server technologies. I cam ...

The JavaScript promise remains in limbo, neither resolving nor rejecting, seemingly stuck for unknown reasons

In the process of developing a node script, I encountered an issue where the images were not being ordered according to the calculated score value. The score is determined by a function named getImageScore(), which unfortunately takes a considerable amount ...

Troubleshooting issue with refreshing selectpicker in Bootstrap-select and Vue.js

Incorporating the bootstrap-select plugin (found at ) into a ruby on rails app with Vue.js as the javascript framework has been my latest project. The goal is to have two select options where one selects a category and the other displays all available tea ...

The functionality of the button is disabled once a pop-up JavaScript is implemented

I have encountered an issue with my HTML code that involves a button intended to hide certain content. The problem arose when I implemented a popup feature, causing the button to malfunction. Here is the JavaScript for the popup: $ = function(id) { retur ...

Scroll bar malfunction in Highcharts

I am struggling to get the scroll bar working so that all categories can be displayed. I have tried different approaches but haven't been able to figure out where I'm going wrong. See the code in action here: http://jsfiddle.net/manraj/7racxxu0/ ...

Dispatch an angular POST Request

I am facing an issue where Angular is sending a GET request instead of a POST request when I want to send a post request. The code for my Angular request is as follows: $http({ method: 'POST', url: pages_url, params: { ...

Is there a way to identify if you are at the bottom row of a column defined by CSS styling?

I have implemented the new CSS-style column to divide a single unordered list into multiple columns. Now, I am trying to figure out how to target the last element in each column using JavaScript or CSS. Here is my HTML: <ul> <li /> <li ...

The instance is referencing "underscore" during render, but it is not defined as a property or method

I have experience as a skilled react developer, but I've taken over a vue.js project from another developer and managed it for quite some time. Regrettably, I haven't put in the effort to learn vue properly. When using lodash, I encountered an u ...

What could be causing the malfunction of this Bootstrap button dropdown?

Initially, I attempted using regular HTML for the dropdown button but encountered issues. As a result, I switched to jsfiddle to troubleshoot. Despite my efforts, the dropdown feature still refused to work. If you'd like to take a closer look, here&a ...

Is there a way to eliminate text from a barcode image using JavaScript or TypeScript?

This is my unique html code <div class="pr-2" style="width: 130px"> <div *ngIf="!element.editing" > <span class="ss">{{element.barcode}}</span> </di ...

Why does the function yield two distinct outcomes?

I can't figure out why, but when I execute the function (kpis1) by itself, it returns the result (100), however, when I run the function (kpis2) alone, I get the result (97). But when I run both functions together, the results are kpis1=100 and kpis2 ...

The functionality of jQuery.hover with AJAX is malfunctioning

I am facing an issue with my jquery hover combined with $.post method. My initial intention was to create a series of select buttons where hovering would trigger a change in the image being displayed (the image path would be loaded via $.post). The image ...