Promise executed out of order, how to resolve?

Asked

Viewed 66 times

0

I’m using the setTimeout function in the form of Promise, following the example of the Mozilla documentation. It turns out that the callback function is running before the end of the counter, immediately after the start of the program.

base function:

function wait(time) {
  return (
    new Promise(resolve => setTimeout(resolve, time))
  )
}

resolution (this that is giving problem):

wait(2000).then(console.log('wating...'))

using async/await works normally:

async function getWait() {
  await wait(2000)
  console.log('wating...')
}

getWait()

2 answers

3

The .then needs a callback function. Without the function, the console.log is executed immediately:

function wait(time) {
  return (
    new Promise(resolve => setTimeout(resolve, time))
  )
}

wait(2000).then( () => {console.log('wating...')})

1

The call then must receive a function (which can be anonymous)

function wait(time) {
  return (
    new Promise(resolve => setTimeout(resolve, time))
  )
}

wait(3000).then(() => console.log('wating 2...'))

async function getWait() {
  await wait(2000)
  console.log('wating 1...')
}
getWait()

console.log("start")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.