Javascript promise failing to deliver

As a beginner in the world of JavaScript development, I am excited to be part of the stackoverflow community and have already gained valuable insights from reading various posts.

Currently, I am facing an issue where I need to load a file, but due to its asynchronous nature, the code is not waiting for it to finish loading. While I attempted using a Promise, it seems to still not wait for the file to load before moving on. Interestingly, it does wait when there's no file present. This behavior is counterintuitive as it should prioritize waiting for the file to load first and then proceed with executing the next function that requires the data from the file. Can someone please shed some light on why my promise implementation is not working? Should I consider using a callback instead?

Below is the snippet of the code causing me trouble:

// ...

var p = new Promise(function (resolve, reject) {
    let x = getTheData(); // async data but program doesn’t wait.
    if (!x) { //if no data, I want to wait?
        resolve('success');
        console.log('success');
    }else {
        reject('failure');
        console.log('failure');
    }
});

p.then(function () {
    let y = getNewFunctionThatNeedsTheAboveDataToWork();
    res.send('y is not working ' + y);
}).catch(function(){
    console.log('error');
});

return p;

I'm feeling completely lost at this point, any guidance would be greatly appreciated.

Answer №1

In this scenario, the issue arises because getData operates asynchronously, requiring a method to determine when it completes its task. This implies that getData must either return a promise (the modern approach) or accept a callback as an argument (the traditional approach). Below is an illustration of how promises can be utilized with getData to fetch data through a web call using pure JavaScript:

var getData = function() {
  var p = new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4 && this.status != 200) {
          console.log('Data request returned an error');
          reject('failure');
      } else if (this.readyState === 4 && this.status === 200) {
          resolve(this.responseText);
      }
    });
    xhr.open("GET", "https://httpbin.org/get", true); // true = async
    xhr.send();
  })
  return(p)
}

This function can then be used as follows:

getData().then(function(d) {
  console.log(d);
  // perform actions with d
})

Alternatively, achieving the same result can be accomplished using a callback:

var getData2 = function (cb) {
  var xhr = new XMLHttpRequest();
  xhr.addEventListener("readystatechange", function () {
    if (this.readyState === 4 && this.status != 200) {
        console.log('Data request returned an error');
        cb(null, "error");
    } else if (this.readyState === 4 && this.status === 200) {
        cb(this.responseText);
    }
  });
  xhr.open("GET", "https://httpbin.org/get", true);
  xhr.send();
}

getData2(function(d, e) {
  if(e) {
    console.log("oops.  there was an error: ", e);
  } else {
    console.log(d);
  }
})

If you are unable to modify the getData function and it utilizes a callback structure, you can transform it into a promise-based function. Here's one approach:

var promiseMe = new Promise(function (resolve, reject) {
  getData2(function(d, e) {
    if(e) {
      reject(e)
    } else {
      resolve(d)
    }
  })
})

promiseMe.then(function(d) {
  console.log(d)
})

EDIT

The previously mentioned methods are intended for browser usage. To implement a similar solution in node.js, consider the following example:

http = require('http');

var getData = function() {
  var p = new Promise(function (resolve, reject) {
    var data = '';
    http.get('http://httpbin.org/get', function(res) {
        res.on('data', (chunk) => {
            data += chunk;
        });

        res.on('end', () => {
            resolve(data);
        });
    })
  })
  return(p)
}
getData().then(function(d) {
    console.log(d)
})

These examples should help clarify the process.

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

Customize Material-UI FAB Hover Color

While working on my project, I encountered an issue with a floating action button that contains an SVG icon nested underneath it. Even though the SVG icon is not in the children prop of the FAB, hovering over the FAB or the SVG icon causes the FAB to chang ...

Create compelling visual representations by utilizing Google charts to draw customized charts based on variable

I have been attempting to create a chart using Google Charts by passing some parameters to the function. I am trying to use these parameters to populate the data, but it doesn't seem to be working as expected. Is it possible to include parameters in t ...

Using TCL/expect to create a log file in XML or JSON format

Is it possible to create the log file in either XML or JSON format using TCL? Currently, the logs are being stored in text format using the log_file. Any suggestions on how to achieve this? ...

Adjust the hue of a circle based on whether the user's position falls within its designated range

I am working with a map that displays several circles, each with its own radius. When the page loads, I capture the user's position and show it on the map. Initially, all circles are red. My goal is to determine if the user's current position fal ...

It appears that the SignalR proxy is not defined

Why is $.connection.connectionhub showing as undefined? I am using webform. <script src="/scripts/jquery-1.6.4.min.js"></script> <!--Reference the SignalR library. --> <script src="/scripts/jquery.signalR-2.2.1.min.js">< ...

When working with NodeJS and an HTML form, I encountered an issue where the 'Endpoint'

Having trouble sending input data from a form to my nodejs endpoint. When I try printing the req.body, it shows up as undefined and I can't figure out why. Here is the relevant API code snippet: var bodyParser = require('body-parser') var e ...

Change UL to a JSON format

I am attempting to transform an entire unordered list (UL) and its child elements into a JSON object. Here is the approach we took: function extractData(element) { element.find('li').each(function () { data.push({ "name": $(this).fi ...

PHP and AJAX collaboration encounters issue with returning JSON data

I'm encountering an issue with the PHP & AJAX login functionality. Upon clicking the Login button, instead of receiving the expected alert, I am redirected to login.php and presented with a JSON response like: {"return":"error"} or {"return":"success" ...

Loading data from JSON files into Postgres tables

In one of my database columns, I have arrays stored as text which look like this: ID | My_data 0 | [[A, 0.1], [B, 0.1]] 1 | [[A, 3.2], [B, 1.1]] : | : 99 | [[B, 0.2], [A, 4.4]] It's important to note that the order of data in these arrays is not ...

Animate a div component sliding out while seamlessly introducing a new one using React

For my signin page, I've set it up so that users first enter their username and then click next to trigger a fluid slide animation which reveals the password field from the right. Although the separate components are already coded and the animation wo ...

Sending an array of elements to an API using Python

I'm currently working on a Python script that sends POST requests to an endpoint in order to create keywords and SMS responses. The goal is to post multiple zip codes and receive a specific response for each one, which should say "sorry, we're cl ...

error: local server did not return any data

I am currently using PHP on a Linux machine. In my HTML code, I have set up an AJAX request to the local Apache server (check http://localhost), with the intention of displaying the data from the server on the screen. However, for some reason, nothing is b ...

Could one harness the power of SO's script for adding color to code within questions?

Similar Question: Syntax highlighting code with Javascript I've observed that Stack Overflow utilizes a script to apply color coding to any code shared in questions and answers, making it resemble how it would appear in an IDE. Is this script pub ...

What is the best way to showcase a set of paired arrays as key-value pairs?

Currently, I am developing a client in React that is responsible for receiving streaming data that represents objects from the back end. The client's task is to parse this data and dynamically construct the object as a JavaScript data structure, typic ...

The compatibility between cross-fetch and React Native is currently not supported

I have developed an API wrapper that utilizes fetch to carry out the API requests. To ensure compatibility with Browsers, Node, and React Native, I incorporate cross-fetch. When testing the wrapper in Node, everything works fine. However, when using it in ...

What is the best way to retrieve a FireStore document ID from an object?

I'm in the process of trying to reference an auto-generated firestore document ID in order to create a subcollection within it. The issue I'm facing is that although I can locate the document ID, I'm struggling to save it to a variable in a ...

Relocating JavaScript scripts to an external file on a webpage served by Node.js' Express

When using Express, I have a route that returns an HTML page like so: app.get('/', function(req, res){ return res.sendFile(path.resolve(__dirname + '/views/index.html')); }); This index.html file contains multiple scripts within t ...

Unexpected behavior: JQuery Ajax request not displaying Json object following recent update to JQuery version 1.10.2

Currently facing an issue with a project I am working on. The previous programmer used jquery 1.4.4, and I have updated it to 1.10.2 due to the designer using Bootstrap. However, after running it in version 1.10.2, one of the objects that was functional i ...

What is the best source for JSON serialization when using Ktor?

Having some trouble sending requests with Kotlin through Ktor. Android Studio doesn't seem to recognize the JSON serialization imports I'm trying to use. Here are the dependencies in my build.gradle.kts (:app): implementation("io.ktor:ktor- ...

Learn the trick to make this floating icon descend gracefully and stick around!

I'm trying to create a scrolling effect for icons on my website where they stay fixed after scrolling down a certain number of pixels. I've managed to make the header fixed after scrolling, but I'm unsure how to achieve this specific effect. ...