2

I was of the understanding that the then() promise method always itself returns a promise. Promises are something I'm still getting used to being a bit of a newb, so I've just been going over some examples and tinkering. The following example shows that the return value of the then method is an object.

const foo = true;

const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        if (foo) {
            resolve('Do this');
        } else {
            reject(Error("Do that"));
        }
    }, 1500)
})

const bar = myPromise.then(value => value);

console.log(typeof bar); // object

Is this the same as returning a promise? Or do I need to explicitly tell then to return a promise like so (pseudocode, I know not correct) :

.then(value => {
    // do something 
    return new Promise;
})

I want to make sure I've got this. Really appreciate the help.

  • you forget `.catch(function(error) {....` – Mister Jojo Jan 26 '20 at 17:45
  • Yes, `then` *always* returns a new promise for the result of the respective callback. *Iff* that callback returns a promise that one will be awaited as well, but if the callback returns a plain value (or even `undefined`) then the promise will simply fulfill with that. – Bergi Jan 26 '20 at 18:02
  • using `await` -> ```const bar = await myPromise.then(value => value); console.log(typeof bar); // string``` – ajai Jothi Jan 26 '20 at 18:22
  • `typeof` won't tell you if something is a promise. It returns `"object"` for almost any kind of object, including promises. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof – JLRishe Jan 26 '20 at 18:23

2 Answers2

4

Yes, The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.

And the promise is an object and the typeof promise will be an object. You don't need to explicit return a promise.

You can read more about the promises here

Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42
0

Yeah then() always return a promise. However, the pseudocode is incorrect. The function then takes two arguments:

p.then(onFulfilled[, onRejected]);

p.then(value => {
  // fulfillment
}, reason => {
  // rejection
});

Exactly like the Promise constructor. Then create a promise from another one. We often omit the onRejected argument because of we handle the reject case with catch.

Here an interesting article: https://medium.com/@kevinyckim33/what-are-promises-in-javascript-f1a5fc5b34bf

And the then doc : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

Louis Singer
  • 767
  • 1
  • 9
  • 18