Async/Await

Status
Not open for further replies.

LeChris

github.com/habbo-hotel
Sep 30, 2013
2,725
1,306
This is a test function

The results do not return in the order the code is called in. I'm interested in what I'm doing wrong or if this is a possible bug?

Doesn't Return In Order
PHP:
// Async functions
async function one() {
  setTimeout(() => {
    console.log(1)
    return true
  }, 5000)
}

async function two() {
  console.log(2)
  return true
}

async function three() {
  setTimeout(() => {
    console.log(3)
    return true
  }, 1500)
}

// Primary Function
async function init() {
  let result = {}
  result = await one()
  result = await two()
  result = await three()
  console.log('Finished')
}


// Call It
init()


Does Return In Order
PHP:
console.log('\n\n\n\n\n\n\n')// Async functions
async function one() {
  return new Promise ((resolve, reject) => {
    setTimeout(() => {
      console.log(1)
      resolve()
    }, 10000)
  })
}

async function two() {
  console.log(2)
  return;
}

async function three() {
  return new Promise ((resolve, reject) => {
    setTimeout(() => {
      console.log(3)
      resolve()
    }, 1000)
  })
}

// Primary Function
async function init() {
  await one()
  await two()
  await three(0)
}


// Call It
init()

 
Maybe my understanding of Async/Await is bad - and I'm trying to handle async code in a sync way as each promise does resolve, just not in the intended order.
 
Last edited:

Adil

DevBest CEO
May 28, 2011
1,276
713
From what I understand you want to resolve promises in sequential order?
You could look into using something like this
 

RastaLulz

fight teh power
Staff member
May 3, 2010
3,926
3,920
You're misunderstanding how async/await works; it's essentially a sugarcoated promise. For instance, if an async function gets to the end before needing to await on anything, that function has "resolved" at that point. It's not going to wait for the setTimeout, since it doesn't know it has to.
 

LeChris

github.com/habbo-hotel
Sep 30, 2013
2,725
1,306
You're misunderstanding how async/await works; it's essentially a sugarcoated promise. For instance, if an async function gets to the end before needing to await on anything, that function has "resolved" at that point. It's not going to wait for the setTimeout, since it doesn't know it has to.
I understood it was sugarcoated promises - but didn't understand how it handles things such as that. Much thanks
From what I understand you want to resolve promises in sequential order?
You could look into using something like this
That is correct

Also
This has been resolved by @Virtuex
drvKU1E.png
 
Status
Not open for further replies.

Users who are viewing this thread

Top