If the then method of promise in nodejs returns not a promise but a numeric value, what will happen to the next then method?

In the Promise chain, if a then method returns not a Promise object, but an ordinary value (such as a number), then the next thenThe method will continue to execute with this value as parameter. This value will be wrapped into a resolved Promise and then passed to the nextthen method. In this case, the Promise chain will still maintain the normal execution flow, even if a Promise is not returned.

Here is a simple example that demonstrates this situation:

const promise = new Promise((resolve, reject) => {
    
    
  resolve(42); // Resolving with a number
});

promise.then(value => {
    
    
  console.log(value); // Output: 42
  return 100; // Returning a number, not a Promise
}).then(newValue => {
    
    
  console.log(newValue); // Output: 100
});

In this example, the firstthen method returns a number 100 instead of a Promise object. The next then method will still be executed normally and use the number returned by the previous then method as a parameter.

It should be noted that even if a Promise is not returned, the execution sequence of the then method is still asynchronous, because the characteristics of Promise ensure asynchronous execution.

Guess you like

Origin blog.csdn.net/weixin_39896629/article/details/134377896