Is it possible to invoke another function if the initial callback does not yield a Promise?

Exploring The Power of Promise Chaining and came across this code snippet:

Promise.resolve(123)
    .then((res) => {
        console.log(res); // 123
        return 456;
    })
    .then((res) => {
        console.log(res); // 456
        return Promise.resolve(123); // Pay attention to the fact that we are returning a 
Promise
    }) 

The first function callback does not return a promise, while the subsequent ones do. Is it possible to call then after the statement

.then((res) => { console.log(res);return 456;})
is executed?

Answer №1

According to @jaromanda-x,

The then function in JavaScript returns a Promise, allowing for method chaining.

By passing a lambda to then and returning a promise, an equivalent Promise is passed down the method chain. The following code snippet demonstrates asynchronous behavior with the setTimout function.

Simply returning a value from within a then lambda will result in

Promise.resolve(<value returned by whichever handler was called>)
.

For example:

var p2 = new Promise(function(resolve, reject) {
  resolve(1);
});

p2.then(function(value) {
  console.log(value); // 1
  return value + 1;
}).then(function(value) {
  console.log(value + '- This synchronous usage is virtually pointless'); // 2- This synchronous usage is virtually pointless
});

p2.then(function(value) {
  console.log(value); // 1
});

Explore more about Promises on MDN

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

An AJAX function nested within another AJAX function

Is there a way for me to return the second ajax call as the result of the ajax function? I could use some assistance with this. function ajax(url: string, method:string, data:any = null) { var _this = this; return this.csrfWithoutDone().done(funct ...

Creating objects in Angular 2 through HTTP GET calls

Recently, I've delved into learning Angular 2. My current challenge involves making http get requests to retrieve data and then constructing objects from that data for later display using templates. If you believe my approach is incorrect, please feel ...

Low resolution icons in Cordova using JQuery Mobile

Currently, I am working on a Cordova application and encountering an issue where the icons appear low resolution when running it on Android or a browser. I came across a solution online advising to add the following code snippet to the meta tag: <meta ...

The getElementsByTagName function is failing to retrieve all of the child nodes

Looking for assistance with XML parsing str = "<ROOT><CATEGORY_AREA_LIST><CATEGORY_AREA NAME='General'><CATEGORY_TYPE NAME='MOC'><PROPOSED_LEVEL NAME='3'></PROPOSED_LEVEL></CATEGORY_TYPE ...

When the submit event is triggered, the window requests permission to open a popup from the browser

I have encountered an issue while working on a project. After users submit their id and password and click on the submit button, I check for user credentials in the database. If there is a match, I want to open a new window without the browser asking for p ...

Is there a way to showcase the results of a countdown timer script within an HTML code?

I'm currently working on a way to incorporate the results of this online timer script into another script. Below is the timer script that I came across: // Setting the target date for the countdown var countDownDate = new Date("Jan 5, 202 ...

Why can't we use percentages to change the max-height property in JavaScript?

I am currently working on creating a responsive menu featuring a hamburger icon. My goal is to have the menu list slide in and out without using jQuery, but instead relying purely on JavaScript. HTML : <div id="animation"> </div> <button ...

Pass information to a Bootstrap modal for processing and execute a MySQL database query

while($row = mysqli_fetch_array($result_from_query)){ <a class="modal-trigger" href="#basicModal" data-toggle="modal" data-target="#basicModal" data-id="<?php echo $row['invoice_no']; ?>"><?php echo $row['invoice_no&ap ...

One-of-a-kind browser identification for users, no login required

I have an online boutique and I want to enable customers to make purchases without creating an account. To achieve this, I need a way to associate a selected list of items with a user. Initially, I considered using the IP address for this purpose but fou ...

Assign specific classes to the rows and overall table by extracting information from the first row and first column of the table

My goal is to utilize jQuery in order to dynamically assign classes to the rows and columns of a table based on the classes of the first row and column. For instance: The current HTML code I have is as follows: <table class="numAlpha" border="1"> ...

Accessing the system through a pop-up window with the help of AJAX and

As a newcomer to the world of AJAX, I must admit that I may have jumped into this field with too much enthusiasm. For several days now, I have been struggling to integrate AJAX with my PHP script. Before dismissing this question as a duplicate, please unde ...

Ensure the unordered list (ul) remains fixed in place

Is there a way to make my left menu, which is a ul, stay static on the screen so that the full menu always appears when I scroll? I attempted to set 'position: fixed; top: 0, left: 0' but it caused the div next to the ul to shift on top of the u ...

The utilization of ReactJS to render basic HTML elements

Completely new to react, I'm not sure if my code is written the "react way". Created some react classes rendering a Bootstrap Modal. Set the initial states by calling an Ajax function within componentsDidMount. Everything works until trying to insert ...

Pass Form ID To Function In A Dynamic Way

I have multiple forms on my webpage and I want to use the same ajax function for all of them. It currently works well for one form by fetching the id with getElementById and then passing it to the ajax function. My goal is to dynamically pass down the form ...

Flipping a binary array?

Is there a optimized method for inverting a binary array of any length? For example, changing all 1s to 0s and all 0s to 1s within the array. var arr1 = [ 0, 0, 1, 1, 1, 0, ..., 1 ]; ...

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

Just easy highlighting using tags in Javascript

I have come across a code snippet that seems to be functioning well: <html> <head> <title>Testing JS Highlighting</title> <script type="text/javascript"> function highlight() { var t = ...

The Next JS build process is failing to generate certain paths

Issue with Anime Database App Deployment A problem arose when I developed an anime database app using Nextjs and deployed it on Vercel. Although the build was successful and the initial page rendered properly, only a few dynamic routes displayed correctly ...

Save an array of messages by making separate API calls for each one

I have a function that makes an API call to retrieve a list of message IDs. Here is the code: function getMessageList(auth) { api.users.messages.list({ auth: auth, userId: 'me', }, function(err, response) { if (er ...

Ways to interact with popup windows using Selenium

I'm currently using Selenium to automate a web task, and I'm facing an issue with clicking on a popup that appears after searching for an address. The popup displays a message asking, "Did you mean _____ address?" and I want to be able to click o ...