M
M
magary42020-07-14 14:45:30
Node.js
magary4, 2020-07-14 14:45:30

Multiple awaits in a row?

const a = await http.get
const b = await http.get

how will this code be executed?
as far as I know await is "syntactic sugar" and will it still be converted to promises?
does it create 2 promises and fulfill them at the same time or does it create one promise and the second one only when the 1st one resolves?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-07-14
@magary4

What does "converted to promises" mean? http.get()in your case, this is the promise.
await is not just syntactic sugar, it is a language construct that blocks any of the following code inside an asynchronous function until the promise passed to it as a parameter has finished executing.
Accordingly, an analogue of your code without using await is

http.get().then(a => http.get().then(b => {
  // Здесь дальнейший код
}))

Example
const p = (resolve, reject) => {
  setTimeout(() => resolve(new Date()), 2000)
}

const syncFn = () => {
  new Promise(p).then(console.log)
  new Promise(p).then(console.log)
}

const asyncFn = async () => {
  const a = await new Promise(p).then(console.log)
  const b = await new Promise(p).then(console.log)  
}

syncFn() 
// Tue Jul 14 2020 15:17:19
// Tue Jul 14 2020 15:17:19

asyncFn()
// Tue Jul 14 2020 15:17:49
// Tue Jul 14 2020 15:17:51

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question