Search code examples
javascripttypescriptecmascript-6es6-promise

Can then be called if the first callback does not return a Promise?


I'm going through Chain-ability of Promises and the code looks like this:

Promise.resolve(123)
    .then((res) => {
        console.log(res); // 123
        return 456;
    })
    .then((res) => {
        console.log(res); // 456
        return Promise.resolve(123); // Notice that we are returning a 
Promise
    }) 

The first callback does not return a promise, but the rest do. Can then be called after the statement .then((res) => { console.log(res);return 456;}) completes?


Solution

  • As @jaromanda-x mentioned,

    The then method returns a Promise which allows for method chaining.

    You can pass a lambda to then and if it returns a promise, an equivalent Promise will be exposed to the subsequent then in the method chain. The below snippet simulates asynchronous code with the setTimout function.

    When a value is simply returned from within a then lambda, it will effectively return Promise.resolve(<value returned by whichever handler was called>).

    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
    });
    

    Read more on MDN