The decision between using multiple then statements or consolidating your code into a single then statement depends on the specific requirements

I am facing a situation where an api call returns data asynchronously and I have 2 methods that need to execute after the call is completed. However, these methods do not generate new promises on their own.

Can

const foo = new Promise(…);

foo.then(() => {
    console.log("foo");
    console.log("bar")
})

Be more advantageous than

const foo = new Promise(…);

foo
    .then(() => console.log("foo"))
    .then(() => console.log("bar"))

?

I understand that chaining then statements can be useful when the first one returns a promise, but is there any benefit to chaining then statements when the initial one does not return a promise?

One possible advantage could be more precise error control:

const foo = new Promise(…);

foo
    .then(() => throw error("Whoopsie"))
    .catch(e => handle(e))
    .then(() => throw error("Daisy"))
    .catch(e => handle(e))

Answer №1

Is there still a benefit to chaining then statements if the initial thenable does not return a promise?

What exactly do you mean by "return a promise"? In all cases, a promise is returned and the resolver's result is based on the current value (excluding errors).

Consider the following example:

p = new Promise( r => r('foo'));
p.then((val) => {console.log(val); return val + 'bar'})
 .then(console.log)
 .then(console.log);
/* output:
foo
foobar
undefined
*/
  1. Using r, the promise starts the chain by processing the value produced by the function in the promise constructor
  2. Next, the subsequent callback is executed on that value, resulting in 'foo' + 'bar'
  3. Then, console.log is invoked but does not return anything (thus returning undefined)
  4. Finally, console.log is called on undefined

Since a promise is always returned, multiple then calls can be made successively. The decision to chain then statements or consolidate your entire function into one callback depends on whether you want your function to be potentially interrupted during its execution.

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

Using 'cy.get' to locate elements in Cypress tutorial

Is there a way to search for one element, and if it's not found, search for another element? cy.get(@firstElement).or(@secondElement).click() Can I use a function similar to || in conditions for this scenario? ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

Verify user identities using just their passwords

For my express app, I'm tasked with creating an authentication system that uses a 4-digit pin as the password. The code is set up to save and hash the pin along with other user information when adding a new user. Since this is for an in-house server h ...

Enhancing MEAN Stack Application by Updating Table Post Database Collection Modification

In my efforts to ensure that my table data remains synchronized with the database information, I have encountered an issue. Whenever Data Changes: $scope.changeStatus = function($event,label,status){ var target = $event.currentTarget; target ...

"Experience the new Bootstrap 5 feature: Off-Canvas sliding from left to

I encountered the code snippet below on the official bootstrap 5 demo. Despite my efforts, I am struggling to figure out how to relocate the off-canvas menu from Left-to-Right. The divergence between the documentation code referencing offcanvas-start and t ...

Using AngularJS to use ng-show, sg-hide, and ng-click

Is there a way to create a Start button that hides when clicked and shows a Stop button instead? When the Stop button is clicked, the Start button should reappear. I've attempted this but it doesn't seem to work. Any suggestions or ideas? &a ...

The settings of the button return to their default state once it is clicked on

I've been working on a small project and I added a button with hover and CSS effects. However, the issue is that once the button is clicked, it reverts back to its basic state without any of the CSS properties applied. I attempted to troubleshoot if ...

Modifying the User Model in Sails.js results in an automatic password update

/** * User.js * * @description :: The User model handles user data, including hash functions for password security. * @docs :: http://sailsjs.org/#!documentation/models */ var bcryptjs = require('bcryptjs'); function hashPassword(values, ...

invoke a fresh PHP page and transmit a lengthy string of text

I have a PHP page named 'main' and would like to trigger another PHP page called 'printpage' when the user clicks the mouse. I need to transfer a large amount of text in this process. Instead of passing the text as a URL parameter, whi ...

VueJS refreshes components while preserving previous data

As a newcomer to VueJs, I am currently working with a Practice component that includes an ExerciseMC component. The parent component retrieves a question object (with a text property) from the backend through a request and passes it as a prop to the Exerci ...

Retrieving data from external JSON files

I implemented this JavaScript code to retrieve JSON data from an external server. The JSON data gets loaded from the server, but I'm unsure how to extract markers from the Google Map using this external JSON data. var map, infowindow; //// // Fet ...

Extracting necessary data from a JSON file and generating a new JSON file with the selected information

My task involves parsing a JSON file to extract events that fall within a specified start and end time provided via an HTTP GET request. The goal is to return these filtered events as a new JSON-encoded response. Despite brainstorming two potential solutio ...

What is the best method for automating the transfer of data from a database to the user interface of a website using html and javascript?

As a volunteer coordinator for a non-profit organization, I have some basic experience working with Python. I am willing to dedicate fewer than 8 hours of learning time to my current project in order to automate certain tasks (or else I will do them manual ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

Showing loading spinner when clicked

I created a spinning animation in CSS, but now I want to hide it and only display it when a button is clicked. I've tried to achieve this using the following code, but the spinner doesn't appear when I click the submit button. To hide the spinne ...

Dropdown menu not populating with options in AngularJS ngOptions

It's puzzling to me why the dropdown menu is not being populated by ng-options. Despite JSON data being returned from the service and successfully logged in the controller, ng-options seems to be failing at its task. <tr class="info"> <td ...

Steps for generating random numbers from a set of given numbers

I am faced with a scenario where I need to generate random numbers based on a given set of numbers. For instance, if I have an array num=[23,56,12,22], I would like to obtain a random number from this array. ...

Tips for sending an icon as a prop in React components

I'm struggling to implement an icon as a prop while using props for "optionText" and "optionIcon". The optionText is working fine, but I'm facing issues with the OptionIcon. File where I'm creating props import Icon from ...

What is the best way to transfer a variable from an @Input property to a service within an Angular2 component?

I'm tackling what seems like a simple task, but I'm struggling to figure it out. My issue is this: How can I successfully pass a variable from @Input to a service in an Angular2 component? (Code has been simplified) This is my current component ...

Loading gltf files with Three.js does not automatically update external variables

When I import a gltf object, it seems to render in the browser but I am unable to access it using an outside variable. What could be causing this issue? let loadedModel; gltfLoader.load('./assets/javaLogo.gltf', function(gltf){ loadedModel = ...