1

I want to debug a function that returns a promise and for that I need a sleep function. I found this one:

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
} 

and it works when used outside of a promise. However when I want to use it in a promise, I get the error, that sleep was not found. This is my code:

async function f(filename) {
  return new Promise((resolve, reject) => {
    await sleep(1000);

    /*
      rest of function
    */
  });
}
user11914177
  • 885
  • 11
  • 33

3 Answers3

1

Try to replace return new Promise((resolve, reject) => {}) in function f with return new Promise(async(resolve, reject) => {}). I hope it will solve your problem

async function f(filename) {
  return new Promise(async (resolve, reject) => {
    await sleep(1000);

    /*
      rest of function
    */
  });
}
Shivanshu Gupta
  • 324
  • 2
  • 9
  • 1
    Except you shouldn't be using `await` inside a promise executor anyway. By definition, you already have promises so you don't need to be wrapping it in another manually created promise. That's an anti-pattern. So, the whole premise of this question is flawed. One shouldn't be making the promise executor `async`. – jfriend00 Jun 20 '20 at 19:50
  • 1
    [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! – Bergi Jun 20 '20 at 20:16
0

However when I want to use it in a promise

You should never create another promise inside the new Promise executor. Instead, call the sleep function inside the surrounding function f (which you already marked as async, presumably to use the await keyword):

async function f(filename) {
  await sleep(1000);
  return new Promise((resolve, reject) => {
    /* rest of function  */
  });
}

Your problem was also that the (resolve, reject) => {…} function is not async, so trying to use await inside there was a syntax error (in strict mode) and might also have caused the error message about the unexpected sleep token after the await.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
-1

Hi try using below code add async in the return code because you are using await inside the return

function sleep(ms) {
    return new Promise((resolve) => {
        console.log('inside sleep');
      setTimeout(resolve, ms);
    });
  } 
   function f(filename) {
    return new Promise( async(resolve, reject) => {
      await sleep(7000);
      
      /*
        rest of function
      */
    });
  }
Shubham Raka
  • 36
  • 1
  • 3