Sending Data to a JavaScript Promise

What is the best way to pass variables into a Promise?

I am in need of a versatile Promise that can be utilized by multiple functions. The Promise is responsible for sending an ajax request to determine the number of entries in a mySQL table and then setting a global variable (let's call it numberOfEntries = #).

The ajax request requires two specific variables to function properly.

var promise = new Promise(function(resolve, reject) { 
var request = $.ajax({
    method: "POST",
    url: "grabDataFromSQL.php",
    data: { data1: variable1, data2: variable2 }
});
request.done(resolve(data));

Therefore, a function using the promise (ultimately accessing the global variable) would follow this structure:

function doSomeStuff() {
promise.then( // complete task here )
}

The promise always necessitates those 2 variables to operate effectively. So... what is the solution? Am I approaching this correctly or is there a flaw in my logic? I seem to be at an impasse.

One possible approach is defining the promise within the same function that calls promise.then() and passing the variables into that function. However, I am hesitant to duplicate all that code repeatedly when the outcome remains consistent each time.

Answer №1

Food for thought:

  1. It's important to note that Promise objects cannot be invoked.
  2. The jqXHR Object returned by $.ajax is said to adhere to the Promise interface.

With this in mind, a possible approach could look something like this:

function handleAjaxRequest(data1, data2) {
    var options = { method: "POST", url: "grabDataFromSQL.php", data: {} };
    options.data.data1 = data1;
    options.data.data2 = data2;
    return $.ajax(options);
}

var promise = handleAjaxRequest(value1, value2);
promise.then(onSuccess, onFailure); // both parameters should be functions

Answer №2

Wow, just as I was about to finish typing my solution, Traktor53 swooped in with an amazing answer that I will be accepting. However, I'll still share my alternative approach for those who might find it interesting. Traktor53's solution is definitely superior (much neater, and great discovery about the Promise interface).

Here's what I came up with:

Hats off to jfriend00 for shedding some light on certain aspects. My idea involved creating a function that generates and returns the promise. This way, I could easily utilize this function in other parts of my code.

Firstly, I created a function responsible for generating the promise that handles an ajax request to fetch data:

function fetchData(param1, param2) {
var promise = new Promise(function(resolve, reject) {
    var request = $.ajax({
    method: "POST",
    url: "grabDataFromSQL.php",
    data: { data1: param1, data2: param2 }
    });

    request.done(function(data) {
        resolve(data);
    });
    });
    return promise;
}

The next step involves invoking this function whenever the data is needed:

function performTask(param1, param2) {
    var promise = fetchData(param1, param2);

    promise.then(function(data) {
    // make another ajax request using the data from the initial promise
    }, function(error) { });
}

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

CSharp MVC using HTML input field styled with Bootstrap features

I have set up a textbox on my webpage which prompts the user to input a string. Upon pressing a button, this string is compared to find matching fields in the database. Additionally, I have another button that triggers the display of a bootstrap modal wher ...

Having difficulty executing the npm test command for my Angular 2 application

I am currently working on an Angular 2 application, and I am fairly new to it. I have set it up with Cordova app and run it through npm. The app starts without any errors and runs smoothly. However, when I try to run the tests using node (i.e., npm test), ...

What is the best way to modify the CSS of a child element within the context of "$(this)"

On my search results page, each result has an icon to add it to a group. The groups are listed in a hidden UL element on the page with display:none. The issue I'm facing is that when I click on the icon for one result, the UL appears under every sing ...

Switch from using $.ajax to $post when making requests in Rails

After the code snippet below, an ajax call is used for a post request. Now I want to switch from $.ajax to $.post. How do I modify the data in accordance with $.post? $.ajax({ method: "POST", url: "get_object", dataType: "json", data: { ...

Instructions for creating a directional route on a map using highcharts

I am currently working on implementing highcharts maps with flight routes, similar to the visualization shown in this Highchart-maps with flight routes example. My goal is to display the routes in a way that resembles the output illustrated in this expecte ...

Save user's email and password for future logins after the initial login

Is there a way to automatically populate the user's email and password in the login form when they check the "remember me" option and return to log in again? This is for a project using React and Next.js. ...

Exploring IdentityServer3: A Deep Dive into OAuth Flows and Varied Strategies

After developing a REST Web API application, I want to provide other developers with the capability to access those APIs on behalf of the user. To achieve this, I have implemented OAuth authentication with IdentityServer3. Currently, I have successfully ge ...

Generate a specified quantity of elements using jQuery and an integer

I am working with a json file that contains an items category listing various items through an array. This list of items gets updated every few hours. For example: { "items": [ { "name": "Blueberry", "img": "website.com/blueberry.png" } ...

Strategies for aligning a div element in the middle of the screen

Positioned in the center of the current viewport, above all other elements. Compatible across different browsers without relying on third-party plugins, etc. Can be achieved using CSS or JavaScript UPDATE: I attempted to use Javascript's Sys.UI.Dom ...

Issue with a stationary directional light tracking the movement of a rotating object and/or changes in the camera perspective

I've been facing a challenge in implementing a day-night cycle with a directional light in an Earth model using custom shaders. Everything seems to work fine with the night and day maps, as well as the light, as long as I don't manipulate the cam ...

How to update a deeply nested object using a single function in a React component

I have a specific object that requires altering the Ethereum value, for instance; const [reportData, setReportData] = useState({ nameOrganization: "test5", socialMedia: "test", country: "aa", discord: "test", ...

Tips on how to inform the client about an oversized file using Multer

Currently, I am utilizing NodeJs's Multer module for file uploads. When a user attempts to upload a file that is too large, I need to send a response back to the client. The issue lies in the fact that within the onFileSizeLimit function, only the fil ...

Querying with complex aggregations in MongoDB for sorting operations

Can anyone help me with sorting a list of accommodations based on price and number of amenities they offer? The main challenges are converting the price (which is in string format starting with $) to an integer for proper sorting, and determining the cou ...

Converting a Click Event to a Scheduled Event using JavaScript and AJAX

Currently delving into the world of AJAX & JavaScript, I have a question for the knowledgeable individuals out there. I am curious to know how I can transform the code below from an OnClick event to a timed event. For instance, I would like to refres ...

Issues encountered with JavaScript when trying to use the jQuery API

I'm trying to fetch random quotes using a Mashape API, but when I click the button, nothing happens. I've included the JS and HTML code below. Can anyone spot an issue with the JS code? The quote is not displaying in the div. Thank you! $(' ...

The dynamic fields are created by the combobox

Hey there, I have a drop-down menu (combobox) where you can select the number of adults for your booking. <select name="adult_no" id="adult_no"> <option value="">Select</option> <option value="1">1</option> <op ...

AngularJS: How to Implement Multi-select Functionality with Bootstrap Typeahead

I'm currently implementing bootstrap multiselect in my angular project (Bootstrap 2.3) My goal is to achieve a similar functionality using bootstrap typeahead, allowing users to select multiple values from search results. I've tried using the h ...

Exploring the power of chaining collection methods and promises in Node.js HTTP requests

My goal is to extract data from a MongoDB database using the find() method, specifically retrieving documents that have a specified "room" value. From there, I aim to identify all unique values within the array of rooms, based on the key "variety". I initi ...

When clicking to open the md-select on Angular Material 1.1.0, an unwanted [object object] is being appended

Every time I try to open the md-select input, an [object Object] (string) is added to the body tag. Click here to see the md-select input After clicking the md-select once, this is how the body looks ...

Message sent from a website utilizing web scraping technology and a Telegram bot

I am looking to develop a Telegram bot that can automatically send messages after scraping information from a website that requires login using Python and Selenium. The goal is for the bot to provide notifications in Telegram when any updates are made on ...