Creating Multiple Promises in JavaScript: A Comprehensive Guide

How can I link multiple promises together? For example:

var promise = new Promise(function(resolve, reject) {

    // Compose the pull url.
    var pullUrl = 'xxx';

    // Use request library.
    request(pullUrl, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            // Resolve the result.
            resolve(true);
        } else {
            reject(Error(false));
        }
    });

});

promise.then(function(result) {

    // Stop here if it is false.
    if (result !== false) {
        // Compose the pull url.
        var pullUrl = 'xxx';

        // Use request library.
        request(pullUrl, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body); // <-- I want to pass the result to the next promise.
            } else {
                reject(Error(false));
            }
        });
    }

}, function(err) {
    // handle error
});

promise.then(function(result) {

    // Stop here if it is false.
    if (result !== false) {
        // handle success.
        console.log(result);
    }
}, function(err) {
    // handle error.
});

Error:

resolve(body); ReferenceError: resolve is not defined

Any suggestions on what might be causing this issue?

Answer №1

When connecting Promises in a chain, the return value from a function passed to `then` should be either a Promise or a value to pass on.

In your situation, since you are making an asynchronous call, you will need to return another promise and utilize `reject` or `resolve` within it. If the operation was synchronous, you could simply return the value or throw an error, which would then be passed to the next `then` or error handler accordingly.

It is important to chain the promises together as each call to `then()` results in a new Promise.

For example:

var promise = new Promise(function(resolve, reject) {

    // Create the pull URL.
    var pullUrl = 'xxx';

    // Use request library.
    request(pullUrl, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            // Resolve the result.
            resolve(true);
        } else {
            reject(Error(false));
        }
    });

});

promise.then(function(result) {

    // Stop here if result is false.
    if (result !== false) {
        var airportCode = result;

        // Compose the pull url.
        var pullUrl = 'xxx';

        // Utilize request library.
        return new Promise(function (resolve, reject) {
            request(pullUrl, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    resolve(body);
                } else {
                    reject(Error(false));
                }
            });
        });
    }

}).then(function(result) {
    // Stop here if result is false.
    if (result !== false) {
        // handle success.
        console.log(result);
    }
}).catch(function (err) {
  // handle error
});

Check out this working version on JSFiddle: JSFiddle

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

What is the method for determining the line number of a specific string within a byte array?

Looking for: The location of a function definition within a code file. What I have: The code file. The byte index where the function definition begins and its length in bytes. How can I determine the line number of this function in the file? My plan: ...

To begin, formulating a blank state entity containing a collection of key-value pairs with JSON objects as the values. Subsequently, modifying the contents of

I am working on setting up a reactJS state with an empty array to start. When I receive a message in the form of a JSON object, I want to add a key-value pair to the array, using the received message as the value and a specified key. For example: We have ...

Bidirectional communication between server and client using socket.io in node.js

I'm currently working on developing a server code in node.js where the client, running on a browser, will send data to the server when a specific ".on" event occurs. The task on the server side is to receive this incoming data from the client and then ...

Implementing a Reset Button to Clear Checkboxes with PHP or JavaScript

I'm looking for help with setting up a button to reset the checkboxes on my preferences page. UPDATEL: Here's more information: The solutions provided should only affect checkboxes that are currently selected, not those enabled onLoad. This is ...

Complete the modal window form

I'm currently facing an issue with populating a modal window form. To provide some context, when I click on a grid row to edit a user, I make an ajax call which fetches specific data related to that user. Here is the existing code snippet: <modal ...

Rendering deeply nested data in a Vue table

I am currently in the process of updating some older code, transitioning to Vue as a replacement. Everything has been going smoothly except for one specific table that is templated using handlebars. With handlebars and nested {{each}} loops, I can easily ...

Is there a way to generate a webpage using data from events emitted by an EventEmitter? How should I go about solving this?

I am currently utilizing Express to generate a web page with custom HTML content retrieved from an eventEmitter. This is the basic structure of my code: app.post("/login", (req, res) => { let factory = eventFactory(args); let client = factory.clien ...

Running Node.js code from npm within Swift can be achieved by following these steps:

I am looking to integrate a Node JS package downloaded from npm into my Cocoa App and run it using Swift. Despite searching online, I have not been able to find any information on whether it is possible to call an npm package from Swift. Can anyone help m ...

What is the best way to access dropdown sub-menu options from a complex multi-level navigation bar

Struggling to figure out how to open my dropdown sub-menu using CSS. Hoping to make it so the user can open it by hovering over the corresponding tag. I attempted to use #lablinksDD to trigger the opening of #ddSbMenu when hovered over #menuDD with #labLin ...

Utilizing Font Awesome icons dynamically presents challenges when integrating with SVG & JavaScript

Recently, I started using the new JS&SVG implementation of font-awesome's v5 icons. It seems to be working perfectly for icons (such as <i class='fas fa-home'></i>) that are already present in the DOM at page load. The <i& ...

Verify whether a variable is empty or not, within the sequence flows in Camunda Modeler

When working with a sequenceFlow in a process instance, I need to check a condition that may involve a variable that has not been defined yet. I want the flow to proceed even if the variable is not defined, rather than throwing an ActivitiException. I hav ...

I'm a bit puzzled by a particular function that was explained in a section of my coding bootcamp module

I'm currently delving into express.js and trying to understand the inner workings of a function that retrieves detailed information about animals based on a query. This function is designed to search for animals by name and return all relevant data, b ...

Lack of Typescript 2.1 and Angular 2 type definitions with browserify

` vscode 1.7 Typescript 2.1.1 Angular 2 latest package.json "dependencies": { "@angular/common": "^2.2.4", "@angular/compiler": "^2.2.4", "@angular/core": "^2.2.4", "@angular/platform-browser": "^2.2.4", "@angular/platform-browser-dyna ...

Developing fresh sessions for every request promptly

I am facing an issue with express-session where it intermittently creates a new session (new sessionID) for each request. Sometimes, it works fine for the first few hits and then suddenly creates a new session on the next hit. This problem only occurs on m ...

Why is the imported package not being recognized in the namespace declaration of my Node.js TypeScript file?

Currently, I am utilizing the WebStorm IDE developed by JetBrains to modify a TypeScript file within a Node.js v8.6.0 project. The JavaScript version set for this project is JSX Harmony. In the beginning of the TypeScript source file, there is an import st ...

Filtering data at different levels in Javascript/Javascript programming language

Consider this array: var selection = ["14-3","19-5", "23-5", "40-8", "41-8"]; We now have two separate arrays: Array1 includes the first part of each value (before hyphens) in the original array, such as 1 ...

Finding the right way to cancel a Firestore stream within a Vue component using the onInvalidate callback

Currently, I am utilizing Vue 3 to develop a Firebase composable that is responsible for subscribing to an onSnapshot() stream. I have been attempting to unsubscribe from this stream by invoking the returned unsubscribe() function within both watchEffect ...

Is it possible to set up multiple registries within a single package.json configuration?

Is it possible to define two different registries within the publishConfig section of the package.json file? The scenario is that we want to publish the artifact to two different locations depending on its purpose. For SNAPSHOT versions, we would like to ...

Having trouble setting a value as a variable? It seems like the selection process is not functioning properly

My Hangman game has different topics such as cities and animals. When a user selects a topic, the outcome should be a random item from that specific topic. For example: London for cities or Zebra for animals. Currently, I am only generating a random lett ...

Tips for using the useState hook to modify an array by its index?

I am working on a select component that needs to update values in an array of objects based on the index. Utilizing the hook as follows: const [areas, setAreas] = useState(product.areas); This is how the "areas" array looks: [ 0: {de: "Getraenke", en: ...