What is wrong with this promise chain? final result should be console.log(4)

Viewed 37

i am trying to understand promises, and i figured i would start by writing a very simple promise chain, that adds 1 to the previous result.

However, it seems like my functions aren't being recognised as such. i have declared the functions on the same page, so it should be straightforward enough, yet i keep getting this error.

I have been following web mdn pretty closely and basically just tried to follow their setup.

what am i overlooking here?

I don't feel confident moving on before i can truly play around with the basics.

doSomething()
  .then((result) => doSomethingElse(result))
  .then((newResult) => doThirdThing(newResult))
  .then((finalResult) => {
    console.log(`Got the final result: ${finalResult}`);
  })
  .catch(failureCallback);

function doSomething(){
  a = 1 + 1
  return a
}

function doSomethingElse(param){
  b = param + 1
  return b
}

function doThirdThing(param){
  c = param + 1
  return c
}

function failureCallback(){
  console.log('it did not work')
}

2 Answers

None of your functions are returning promise. For the promise chain to work, they must all return promises.

EDIT: as @mousetail pointed out, indeed only the first function doSomething needs to return a promise. Thereafter, the then callbacks create and return the promise for you

Here's a working fiddle: https://jsfiddle.net/zjaoyvcr/

The doSomething() function is not returning the promise. 2 Way to resolve that issue.

Method - 1 : Add async before doSomething()

async function doSomething(){
  a = 1 + 1
  return a;
}

Method - 2 : Return promise in doSomething()

function doSomething(){
   a = 1 + 1
   return Promise.resolve(a);
}
Related