Employing a function to concatenate promises

In my coding process, I have come across a situation where I need to fetch content and then save it using two separate functions. Each function performs a different task based on the type of content provided. These functions act as helper functions in my overall code structure.

Initially, I was using asyncfuncA().then(asyncFuncB).then(...); but I realized that I could create a new function that chains A and B together for more streamlined execution. However, I encountered a problem while trying to implement this idea. The simplified code snippet below illustrates the concept I am aiming for.


function getCont(url) {
    return new Promise(function(resolve, reject) {
        // Actual code makes a request and resolves with response body or rejects with an error
        resolve("response body");
    });
}

function saveFile(path, data) {
    return new Promise(function(resolve, reject) {
        // Actual code writes file and resolves true for success or rejects for error
        resolve(true);
    });
}

saveCont("some://url", "/some/path").then(function() {
    // Execute specific actions for one type of content
});

saveCont("another://url", "/another/path").then(function() {
    // Perform different actions for another type of content
});

function saveCont(url, path) {
    getCont(url)
    .then(function(content) {
        saveFile(path, data);
    })
    .then(function() {
        // ** Unsure about what should be included here ??

    });
};

Answer №1

No additional input is required at the end; simply return the Promise object:

function fetchAndSave(url, destination) {
     return fetchData(url)     
     .then(function(response) {
        return saveData(destination, response);   
     });
 };

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

The significance of passing attributes in Webgl2

I'm currently learning about three.js and working my way through the documentation. I'm struggling to understand the meaning behind the following explanation, could someone provide some assistance? When you manually create the WebGL 2 renderin ...

New options for outdated Webpack i18n plugin and loader

I am currently working on a TypeScript project that requires loading translations from individual .json files assigned to each country. For instance, we would have separate language files like en.json, es.json. The goal is to be able to access these trans ...

What is the best way to retrieve the identity or specifics of the item that was right-clicked within the context menu

My AngularJS populated table includes a link button. When I right-click on this button, I've created a specific context menu using jQuery that pops up. The issue arises when I try to retrieve the ID of the item I clicked on in the context menu (such a ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

How can promises be used in place of executing multiple mongoose queries?

Looking for a solution to avoid nested callbacks in the following code: app.get '/performers', (req, res) -> conductor = require('models/conductor').init().model soloist = require('models/soloist').init().model ...

AngularJS xeditable: sending updated data to the server

I am currently utilizing AngularJS to display products in a table for my users. Users have the ability to filter the table using categories or keywords. However, they should also be able to edit the product information within the table, such as product nam ...

Next.js has shifted away from pre-generating page HTML

I have been working on a Jamstack application using Next.js, and I recently realized that the pages stopped pre-generating the HTML content without me noticing it at first. The pages still load fine, but there is no pre-generated HTML. Even the simplest c ...

Storing JavaScript code in a PHP variable fails to function

I've encountered an issue with my JavaScript code. <script> $(document).ready(function(){ $('.delete').click(function() { alert('passed'); }); }); </script> Everything work ...

What is the best way to assign a value to a property in a Controller or Global Variable using jQuery?

On my ASP MVC 5 site, I have a checkbox within the NavBar element. This checkbox's state dictates whether or not the Grid will display Inactive records alongside active ones on each page. In an attempt to have all controllers access the same property ...

Utilize JavaScript to seamlessly play a Spotify track within the Spotify client without disrupting your current

A little while back, I recall the simplicity of clicking play on a song within a website and having it instantly start playing on my computer without any additional steps. It was seamless and effortless. My goal for my website is to have music start playi ...

Can we incorporate various CSS libraries for individual components on our React site?

Let's say, I want to use different CSS libraries for each of my components - Home, About, Contact. Would it be feasible to utilize material ui for Home, semantic ui for About, and bootstrap for Contact? If so, what is the process for incorporating t ...

I'm having trouble with Material Design Slide Toggle as it lacks event.StopPropagation functionality. Any suggestions on what alternative I

When working with the Slide Toggle in Material Design, I noticed that it does not have a stopPropagation event. This is because the "MdSlideToggle.prototype._onChangeEvent" already includes a call to stopPropagation. So, what should be used instead? <m ...

"Steps for implementing a multiselect feature with checkboxes, including the ability to check all and uncheck all, in a React application

After creating a custom component for selecting multiple options and adding a check all feature, the challenge arises when needing an uncheck option. Solution? Implementing an uncheck all feature alongside the select all functionality, but how to modify th ...

Retrieving a map using latitude and longitude coordinates saved in a database

I have a webpage with an embedded Google Map and a dropdown list of cities. The latitude and longitude values for each city are stored in a database. When a user selects a city from the dropdown list and clicks submit, I want the map to load with the corre ...

I can't seem to figure out why I continue to receive the error message stating that 'app.get is not a function'

Below is the code I am currently using: const request = require('request'); const app = require('express'); app.get('/', function (req, res) { res.send('hello world'); }); app.listen(3000); Unfortunately, I keep e ...

The concept of undefined in JavaScript when an if condition is applied

In Node.js, there is a method used to handle API requests. An unusual behavior occurs when dealing with req.query.foo - even if it has a value defined, it becomes undefined when used in an if condition as shown below. Additionally, another req.query.foo ...

What is the best method to calculate the total of multiple input values from various cells and display it in the final cell of an Angular table?

Hey there! I have a challenge where I need to calculate the sum of input values for each cell and display it dynamically in the last cell of the row. Take a look at the image below: https://i.stack.imgur.com/0iKEE.png In the image, you can see that the nu ...

Exploring nested components traversal in React

In my project, I have created a product component that displays the products' name, price, and description. const Product = (props) =>{ return( <div> <p>Price: {props.price} </p> <p>Name: ...

"Implementing a JavaScript function to dynamically add multiple div elements to a

I am just starting to learn JavaScript. The main div with the ID "row_logic" contains two nested divs. I need help figuring out how to dynamically increment this root div in the format shown below using JavaScript. <div class="row-fluid" id="row_log ...

Is it possible to assign binary content to the src attribute of an img, audio, or video tag?

Picture this scenario: I send an ajax request to my PHP server with the name of an image file, and the server is restricted from sending a direct link to the file. Instead, it must send the file contents using PHP's readfile(); function. Now, when thi ...