0

I tried to understand the nature of Promise, And I ran into a similar question in StackoverFlow but the answer posted doesn't answer the quesiton.

The first Promise I made is as below.

const getPosition = (opts) => {
  const geoPromise = new Promise( (resolve,reject)=>{
    navigator.geolocation.getCurrentPosition(success=>{
      resolve(success)
    }, error=>{ }, opts )    

  })
  return geoPromise;
}

This function returns geoPromise as it is because the function has 'return geoPromise' argument in itself. Therefore, we can attach .then after the function like below.

  getPosition()
    .then((posData) => {
      positionData = posData;
      return setTimer(3000) 
    })

However, to attach one more .then after this, I have to return "setTimer(3000)". Even if the setTimer function has return in itself exactly same as getPosition() function.

const setTimer = duration => {
  const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Done!');
    }, duration);
  });
  return promise;
};

So I strongly believed that I don't have to put 'return' to this case as well, then take the 'return' out and it worked in a different way from what I exepcted. What actually happend is Javascript passed this step and excuted the next '.then()' out of sudden, which is 'console.log'.

Why do I have to return setTimer even if I have return in itself and why javscript skips this promise and execute the next promise right away?

  getPosition()
    .then((posData) => { 
      positionData = posData;
      return setTimer(2000) 
    })
    .then(data => {
      console.log(data, positionData);
thesamiroli
  • 420
  • 3
  • 8
  • 21
BS100
  • 823
  • 6
  • 22
  • and consider `navigator.geolocation.getCurrentPosition(x => resolve(x), e => reject(e), opts)` or `navigator.geolocation.getCurrentPosition(resolve, reject, opts)` – Mulan Jun 01 '20 at 03:35
  • you have to put a `return` statement before `setTimer` function call to return the value returned by `setTimer` function – Yousaf Jun 01 '20 at 03:37
  • @Yousaf Hi, thank you for your response. What you meant is even if function returns something to return the value that the function is returnning, I have to return the function as well right? If so, how getPosition() returns its promise even though I didn't put return infront of the getPosition() function? – BS100 Jun 01 '20 at 03:39
  • 1
    in case of `getPosition` function, you are calling it, you are not returning its returned value anywhere. In case of `setTimer` function call, `return` statement is necessary because you want to return the return value of `setTimer` function from the first `then` block so that it is passed to next `then` block – Yousaf Jun 01 '20 at 03:42
  • @Yousaf Thank you sooooo much! Now I understood! really appreciate it – BS100 Jun 01 '20 at 04:03

0 Answers0