Search code examples
javascriptes6-promise

Getting the eventually returned value for promise


Trying to better understand promises. In the following code I'm trying to create two promises that return the numbers 19 and 23 respectively. Then trying to console log the returned value from the first promise but I get promise1.then is not a function. How do I get the value that will eventually get returned from promise1? Thank you.

const promise1 = () => new Promise((resolve, reject) => {
  console.log('inside promise1');
    setTimeout(resolve, 1000, 19);
});

const promise2 = () => new Promise((resolve, reject) => {
    setTimeout(resolve, 3000, 23);
});

promise1.then(d => console.log(d));

Solution

  • You are almost there. Promise1 is a function that returns a promise. the reason for the error is because you are not calling promise1 as a function.

    add bracket to the calling code.

    promise1().then(d => console.log(d));
    

    The full code:

    const promise1 = () => new Promise((resolve, reject) => {
      console.log('inside promise1');
        setTimeout(resolve, 1000, 19);
    });
    
    const promise2 = () => new Promise((resolve, reject) => {
        setTimeout(resolve, 3000, 23);
    });
    
    promise1().then(d => console.log(d));