I have a recursive promise which will poll something 5 time before resolving.
let retries = 0
function poll(i) {
return new Promise((resolve, reject) => {
if (retries === 5) throw new Error('done')
if (i === 0) return resolve('foo')
else retries++
console.log(i - 1)
return poll(i - 1)
})
}
But if i call the function like so, i cannot access the resolved data.
poll(4)
.then(data => console.log('result?', data))
.catch(err => console.log('caught err', err))
The only way to access the data from the resolve is to attach a then block on the end of the 'return new Promise' chain like so:
function poll(i) {
return new Promise((resolve, reject) => {
if (retries === 5) throw new Error('done')
if (i === 0) return resolve('foo')
else retries++
console.log(i - 1)
return poll(i - 1)
}).then(data => console.log('result?', data))
}
However, i did manage to get access to the data when calling the poll function by doing the following:
function poll(i) {
if (retries === 5) throw new Error('done')
if (i === 0) return Promise.resolve('foo')
else retries++
console.log(i - 1)
return poll(i - 1)
}
My question is, why did the first snippet of code not work, but the last snippet did?
From what i understand about Promises, Promise.resolve() and resolve() are the same thing?