The main question
Will response1 always contain the response of request1, or is it possible that if request2 resolves faster it would get assigned to the first variable declared?
The MDN page for Promise.all says the following:
Return value
...
A pending Promise in all other cases.
This returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when all the promises in the given iterable have resolved, or if any of the promises reject. See the example about "Asynchronicity or synchronicity of Promise.all" below. Returned values will be in order of the Promises passed, regardless of completion order.
As the returned array is in order, when it is unpacked it is unpacked in order.
The misunderstanding
The order that the promises are executed is not guaranteed as radarbob points out, but the return order is.
Example
Code
function sleepPrintReturn(value) {
return new Promise((resolve, reject) => {
const delay = Math.random() * 1000
setTimeout(() => {
console.log("Completed", value)
resolve(value)
}, delay)
})
}
(async () => {
const [a,b,c] = await Promise.all([
sleepPrintReturn("a"),
sleepPrintReturn("b"),
sleepPrintReturn("c")
])
console.log("-------------")
console.log(a)
console.log(b)
console.log(c)
})()
Runs
1
Completed c
Completed b
Completed a
-------------
a
b
c
2
Completed b
Completed a
Completed c
-------------
a
b
c