Executing numerous JavaScript Promises simultaneously using the RSVP.js Promise Library

In the JavaScript demo below, the RSVP.js Promise Library is utilized to load JSON data using AJAX. Once the JSON data is loaded, additional Promises are desired that do not involve AJAX requests.

One of the requirements after loading the JSON data is to create a new Promise that will execute a function responsible for setting up DOM Event handlers/listeners.

Following the setup of Event handling, another function needs to be executed after all events have been set up.

Due to being new to Promises and still learning JavaScript, assistance in adding more Promises to the code would be greatly appreciated. An example code expansion with guidance on JSFiddle would be very helpful!

To view the JSFiddle Demo of the code, click here: http://jsfiddle.net/jasondavis/fttzoggj/


var jsonPromiseCache = {};

// Function to load JSON data via AJAX using Promise()
var getJsonDataPromise = function(url, key) {
  if (!jsonPromiseCache[key]) {
    jsonPromiseCache[key] = new RSVP.Promise(function(resolve, reject){
      var client = new XMLHttpRequest();
      client.open("GET", url);
      client.onreadystatechange = handler;
      client.responseType = "json";
      client.setRequestHeader("Accept", "application/json");
      client.send();

      function handler() {
        if (this.readyState === this.DONE) {
          if (this.status === 200) {
            jsonPromiseCache[key] = this.response;
            resolve(this.response);
          } else {
            reject(this);
          }
        }
      };
    });
  }
  return jsonPromiseCache[key];
};

// EXAMPLE USAGE DEMO
var promises = {
  users: getJsonDataPromise('/echo/json/', 'users'),
  task: getJsonDataPromise('/echo/json/', 'task')
};

RSVP.hash(promises)
.then(function(results) {
  // Additional operations after successful loading of JSON data
})
.finally(function(){
  console.log('finally() function ran on success and failure.... It is always ran!');
})
.catch(function(reason){
  console.log('[ERROR] REASON:',reason.statusText); 
});

UPDATE

An updated version of the JSFiddle demo can be found here. The update includes a new function initDomEvents() called within a then(initDomEvents) function. Despite seeing positive execution in the console, an error seems to be triggered.

Answer №1

Everything in my console seems to be running smoothly, but now I'm encountering an unexpected error.

In the function initDomEvents, make sure not to call the resolve and reject functions directly. These functions are meant to be passed as arguments to the new RSVP.Promise(…) callback. Calling them directly will throw an error that is caught and sent to your error handler (without a .statusText property, resulting in only undefined being displayed).

As mentioned earlier, if your function doesn't involve any asynchronous tasks, there's no need to return a promise. Simply use return to provide a value or throw to raise an exception from within your promise callback.
If you still wish to wrap your results or rejections in promises, consider using RSVP.Promise.resolve(…) or RSVP.Promise.reject(…) to create fulfilled or rejected promise objects.

Answer №2

Is there a particular motive behind your choice to utilize RSVP? Switching to jQuery Promises might be a more efficient solution.

var promise = $.Deferred();

$.ajax({
 url: apiURL,
 cache: true,
 dataType: 'json',
 success: function(response){
   promise.resolve(response);
 },
 error: function(err){
   promise.reject();
 }
});

$.when(promise).then(function(result){
     //process the result
});

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

Filling form fields with array data (AngularJS)

Although I'm new to AngularJS, I'm struggling to figure out how to handle a list of arrays returned from the searchAll function. console 0: {mobile: "12345678", lastname: "last01", firstname: "first01"} 1: {mobile: "87654321", lastname: ...

Received an error while working on web development in Bootstrap with npm

I recently watched a freeCodeCamp video tutorial on web development which can be found here. Despite following the tutorial step by step, I encountered the following error message while running the webpack script: PS C:\Admin-Dashboard> npx webpac ...

employing express.json() post raw-body

Within my Express application, I am aiming to validate the length of the request body and restrict it irrespective of the content type. Additionally, I wish to parse the body only if the content type is JSON. How can I go about accomplishing this? Curren ...

Asynchronous Database Operations in Javascript

Being new to AWS databases, Node.JS, and Express, I am facing the challenge of making multiple queries to an AWS DynamoDB database while summing all device_id counts and looping through all the bins. Although my code is incomplete in terms of query paramet ...

Manipulate objects within an array by updating state with a button in React

So, I have an array of names that I want to cycle through: const data = { names: [ { name: "Jordan" // additional data }, { name: "Holly" // additional data }, { name: "Sean" // additional data ...

Most effective approach to setting up a timer using Javascript and PHP

I'm currently working on a quiz application using PHP and Javascript. The quiz begins once the user clicks a submit button, but I want it to end after a specific duration that I define. I'm hesitant to rely solely on the client-side clock as it c ...

Displaying JSON data based on a specific key

My current challenge involves dealing with a JSON string structured like this: {"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]} As part of my learning process in Javascript and AJAX, I am attempting to display the different values based ...

Unable to call Success function in JQuery AJAX request

Here is a simple JQuery ajax request I am working on: $.ajax("../ajax/data/items.json", { success: setContent, type: "GET", dataType: "json" }); function setContent(data, status, jqxhr) { alert("Hello!"); } The json file loads successfully with a 200 r ...

Tips for repairing damaged HTML in React employ are:- Identify the issues

I've encountered a situation where I have HTML stored as a string. After subsetting the code, I end up with something like this: <div>loremlalal..<p>dsdM</p> - that's all How can I efficiently parse this HTML to get the correct ...

Insert a new row into the table using jQuery right above the button

I am working on a table where I need to dynamically add rows in the same rowId upon clicking a specific button. For instance, when the "Add Row 1" button is clicked, a new row should be added under "Some content 1", and so on for other rows. <table i ...

Issue: [AppRoutes] is not recognized as a valid <Route> component

Currently diving into React-Router with guidance from this helpful tutorial: https://blog.logrocket.com/complete-guide-authentication-with-react-router-v6/ Here's a snippet from my App.jsx: import { Route, createBrowserRouter, createRoutesFromE ...

It seems like my ajax function is functioning properly, but the data is not getting submitted

Having trouble sending the value of my selector to a PHP file through AJAX. The success function is working, and when I directly visit "your_php_script.php" it functions as expected. However, why is the PHP page not showing up on the page with the AJAX r ...

In the realm of Vue, the proper way of writing is to follow the first method, while the second approach is considered incorrect. But why is that the case

{{str.split('').reverse().join()}} {{arr.reverse().join()}} An issue arises when attempting to execute the second line of code. There is a possibility of encountering an infinite update loop within a component render function. ...

Utilizing Promise.all with Axios in a Node.js environment

I seem to be facing a challenge in waiting for results from multiple axios promises before proceeding with further processing. The console.log("test"); statement gets executed prematurely, before the completion of other method calls. I suspect that the way ...

Tips for transferring the name field to a different page upon clicking

There are two pages in my project - the first one is called ItemMenuPage and the second one is called CartPage. The functionality I am trying to achieve is that when a user clicks on any item name on the ItemMenuPage, it should navigate to the CartPage, wi ...

I only notice certain text after carefully inspecting the elements in Google Chrome

While creating an application on Sitefinity (ASP.NET), I encountered an issue where certain elements, such as button text and labels, were not loading correctly when running the application. However, upon inspecting the element, they appeared to be working ...

Vue.js is displaying API data in the browser's console, but it is not appearing on the webpage

I am currently learning about API design and attempting to make an API call that retrieves data from an online API server using the vue.js project through CLI. While I can see the results in the browser console, I'm encountering issues with displaying ...

Unable to store multiple users in MongoDB

Currently, I am encountering an issue with passportJS not saving more than one user to MongoDB while using nodeJS with the expressJS server framework. Initially, I successfully set up email registration with passport-local. However, when I added passport- ...

Having trouble with a switch statement in Javascript that is unable to find a case for "none."

In my code, I am checking to see if there is a ball in a specific map point and then changing the color of the pixels where the ball is located to match the color of the ball. Here is my code snippet: function UpdateColorInMapPoints(mapPointIndexs) { / ...

Exploring jQuery's class attribute: Uncovering the key-value pair trick

I am encountering difficulties in obtaining the class of my div elements, which are intended to function as tabs on a simple asp.net website. I aim to achieve this using jQuery for better control over dynamic functions in the future. However, every time I ...