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);