The proper way to link various asynchronous operations enclosed in promises

My current understanding of promises is that they serve as a wrapper for async functions within the outer environment (such as the browser or node.js). However, I am struggling with how to properly connect async operations using promises in software development. Here is the issue I've encountered:

In the code snippet below, a setTimeout function is wrapped in a promise, along with an XMLHttpRequest call. Initially, I assumed that chaining them together would result in the timer running first and then followed by the AJAX call. However, this wasn't the case as the AJAX call executed before the timer.

timer(1000).then(AJAXGetRequest('https://itunes.apple.com/hk/rss/topalbums/limit=10/json'))

I found that rewriting my promise chain like the following produced the expected results:

timer(1000).then(function(){
    AJAXGetRequest('https://itunes.apple.com/hk/rss/topalbums/limit=10/json')
})

The drawback of the above code is that it resorts back to using callbacks for async operations. I believe there must be a way to structure my code without reverting back to callbacks, possibly something like this:

timer(1000)
    .then(AJAXGetRequest('some/api'))
    .then(timer)  // wait
    .then(AJAXGetRequest('someOther/api'))
    .then(timer)  // wait
    .then(AJAXGetRequest('another/api'))
                  // wait

Or perhaps even more flexible:

timer(1000)
    .then(AJAXGetRequest('some/api'))
    .then(timer(200))  // wait
    .then(AJAXGetRequest('someOther/api'))
    .then(timer(600))  // wait
    .then(AJAXGetRequest('another/api'))
                  // wait

Below you'll find the remaining code related to the examples mentioned above:

let timer = function(value) {
    return new Promise((resolve, reject) => {

        setTimeout(() => {

            console.log(value);
            resolve(value); 

        }, value);

    });
};


let AJAXGetRequest = function(URL) {
    return new Promise((resolve, reject) => {

        var getRequest = new XMLHttpRequest();
        getRequest.open('get', URL, true);
        getRequest.send();

        getRequest.onload = function() {

            var JSONObject = JSON.parse(getRequest.responseText);
            console.log(JSONObject);
            resolve(JSONObject); // object
        }


    });
};

Answer №1

<Promise>.then function requires a promise, otherwise it will not be able to process the information.

To address this issue, make sure that what you provide to .then matches the required signature:

timer(1000)
.then(() => AjaxRequest(url1))
.then(() => timer(1000))
.then(() => AjaxRequest(url2))
.then(() => timer(1000));

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

Encountering a problem with serializing forms using jQuery

Currently, I am working on form serialization in order to send the file name to the server. However, I have encountered an issue where the serialization values are empty and I am expecting the file name to be included. Within my form, there is an HTML fil ...

Encountering a jQuery error while trying to utilize the $window.load

I have a code snippet that is functioning well when wrapped within a document ready event: jQuery(document).ready(function($) { $('tr[data-name="background_colour"] input.wp-color-picker').each(function() { //this section works fin ...

Discovering the most recent Node.js version: A step-by-step guide

Is it possible to check the latest available Nodejs version using npm? While node -v allows us to see the current version, I am curious if there is a way to access the most recent version through JavaScript. For example, process.version can be used to vi ...

Issue with floating date and time not functioning properly in ICS file for Yahoo Calendar

I have set up a calendar event in Google, Apple, and Yahoo calendars for each individual customer. The event is scheduled based on the customer's address at a specific time, so there should be no need for timezone conversion. However, I encountered an ...

Is it possible for the scroll event to be triggered while scrolling only when a div element is used?

While utilizing window.onscroll to track scroll events during scrolling, I noticed that in certain Android devices the scroll event is only triggered after the scroll has completed. However, when monitoring scroll events within a specific div element, it ...

Converting nested JSON to CSV for simplified data organization

I need help flattening JSON in order to parse it as a CSV. The current flattening process is not working correctly, as the customer.addresses field is being filled with 'addresstype: r' and then skipping all other fields such as city, countrycode ...

Change PHP code to a JSON file format

I am currently learning Laravel and my current focus is on how to send a JSON file from the back end to the front-end. I intend to utilize this JSON data to generate a graph. Within my model, I have created a function that retrieves values and timestamps ...

The test does not pass when attempting to use a shorthand operator to ascertain the truthfulness of

I've encountered an interesting issue with my unit test. It seems to work perfectly fine when I directly return true or false, but fails when I try to use a shorthand method to determine the result. Let's say I have a function called isMatched w ...

Steps for placing a second pie chart alongside the initial one within a Bootstrap card

Is it possible to have two pie charts with different values using chart.js? I attempted to duplicate the script for the first chart to create a second one, but it did not display correctly. Why is the second pie chart not showing up? $(document).ready(fu ...

Encountering a 404 error when attempting to make an Axios post request

Utilizing Axios for fetching data from my backend endpoint has been resulting in a 404 error. Oddly enough, when I manually enter the URI provided in the error message into the browser, it connects successfully and returns an empty object as expected. Her ...

HTML5 Embedding a redirect iframe for connection status validation [UPDATE]

I've created an offline HTML file and embedded an iframe within it that redirects to a site if there is an available internet connection. However, in the event of no internet connection, the iframe will redirect to an offline page. Could someone plea ...

Guide on Crafting an Interactive Breadcrumbs Component

How can I implement product category breadcrumbs on the product page? These breadcrumbs will represent the parent category of the product. I am utilizing Next.js and Strapi for this project. For example, here is a screenshot showing how it should look: ...

Is there a quicker method to update the state of an array of objects?

Here is my React state example: const [questionList, setQuestionList] = useState([ { _type: "radio", answer: "", point: "", question: "", options: ["A", "B"], ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

Dividing a string yields varying outcomes when stored in a variable compared to when it is displayed using console.log()

When the `$location` changes, a simple function is executed as shown below. The issue arises when the assignment of `$location.path().split("/")` returns `["browser"]` for `$location.path() == "/browser"`, but when run directly inside the `console.log`, ...

Simple steps to validate an ajax response with a specific string

I'm encountering a problem with a simple ajax call that involves checking the returned text against a string: // in my php file echo 'mystring'; // in my javascript if((request.readyState == 4) && (request.status == 200)){ if(req ...

Learn how to collapse a list by clicking outside of it on the document with the following code: $(document).on("click"

I want to create a collapsible/expandable menu for my website. I had a version where hovering over a category would expand the subcategory, but what I really need is for the subcategories to expand when I click on a category and remain expanded until I cli ...

Delete an item from an array when a dropdown selection is made

When dealing with Angular 8, I encountered a logic issue. There are two drop-down menus: First Drop-down The options in the first menu are populated from an array of objects Example Code, ts: {rs_id: "a5f100d5-bc88-4456-b507-1161575f8819", ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

Retrieve data from an API and store it in a JSON array

My website is having an issue where it's fetching data from an API and displaying it in a table, but all the cells are returning undefined values. The data in the API is structured as an array with multiple datasets inside curly braces that I am unsu ...