0

Right now I have

getUserInfo = (data) => {
    console.log('Getting user info')
    return new Promise((resolve, reject) => {
        if (data === 1)
        return resolve('Hello World')
        resolve(getUserInfo(1))
    })
}

getUserInfo().then(data => console.log(data))

This will console.log Getting user info Getting user info Hello World

That's exactly what I want, calling a promise multiple times and then resolve.

However I want to add a delay between promises so I would like to have: Getting user Info Wait 1 second Getting user Info Hello World

I want to use Promise.delay from bluebird. Any tip on how to go?

I've tried

getUserInfo = (data) => {
    console.log('Getting user info')
    return new Promise.delay(500,(resolve, reject) => {
        if (data === 1)
        return resolve('Hello World')
        resolve(getUserInfo(1))
    })
}

But as resolve data of the promise this returns Function: Getting user info [Function]

Thank you in advance!

LuisPinto
  • 1,667
  • 1
  • 17
  • 36
  • Notice that you cannot "call" a promise, you can only call functions. – Bergi Mar 07 '18 at 14:13
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! You should put the code that calls `getUserInfo` again in a `then` callback. – Bergi Mar 07 '18 at 14:14

1 Answers1

2

Delay is a promise, not a promise constructor. So you can use Promise.delay like any other promise..

Below is maybe what your after ->

const getUserInfo = (data) => {
    console.log('Getting user info')
    return new Promise((resolve, reject) => {
        if (data === 1) {
          return resolve('Hello World')
        }
        return Promise.delay(500).then(
           function ()  { resolve(getUserInfo(1)); }
        );
    })
}

getUserInfo().then(data => console.log(data))
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.1/bluebird.min.js"></script>

Using new async / await, can make things like this much easier.

const getUserInfo =  async (data) => {
    console.log('Getting user info')
    if (data === 1) return "hello World";
    await Promise.delay(500);
    return getUserInfo(1);
}

getUserInfo().then(data => console.log(data))
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.5.1/bluebird.min.js"></script>
Keith
  • 22,005
  • 2
  • 27
  • 44