0

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?

test
  • 107
  • 12
  • You cannot `return` anything from the `new Promise` executor callback. No, `resolve` inside a promise constructor is a very different thing. – Bergi Jul 19 '18 at 17:25
  • See also https://stackoverflow.com/questions/31651610/return-value-of-promises-resolve-reject-functions – Bergi Jul 19 '18 at 17:27
  • Notice that you should `return Promise.reject(…)` instead of `throw`ing in your second snippet. Also, why are you using promises here at all when you're not doing anything asynchronous? – Bergi Jul 19 '18 at 17:28

0 Answers0