I just want to show you that you would have output even if you never used Promise.all
or .then
-
const makePromise = x =>
new Promise(r =>
( console.log("constructing...", x)
, setTimeout(r, 2000, x) // fake 2 second delay
)
)
const a = makePromise("a")
const b = makePromise("b")
const c = makePromise("c")
console.log("construction complete!")
// constructing... "a"
// constructing... "b"
// constructing... "c"
// construction complete!
Above, we construct three (3) promises and output is displayed even though we never used a
, b
, or c
anywhere else in the program.
When we attach .then(handler)
the resolved values are passed to handler
-
const makePromise = x =>
new Promise(r =>
( console.log("constructing...", x)
, setTimeout(r, 2000, x)
)
)
const a = makePromise("a")
const b = makePromise("b")
const c = makePromise("c")
console.log("construction complete!")
// constructing... "a"
// constructing... "b"
// constructing... "c"
// construction complete!
Promise.all([a, b, c])
.then(r => console.log("done!", r))
.catch(e => console.error("error!", e))
// done!
This could mean .then
is called on your promise way later in your program, perhaps even asynchronously -
const makePromise = x =>
new Promise(r =>
( console.log("constructing...", x)
, setTimeout(r, 2000, x)
)
)
const a = makePromise("a")
const b = makePromise("b")
const c = makePromise("c")
console.log("construction complete!")
// constructing... "a"
// constructing... "b"
// constructing... "c"
// construction complete!
const main = () =>
Promise.all([a, b, c])
.then(r => console.log("done!", r))
.catch(e => console.error("error!", e))
console.log("please wait 5 seconds...")
setTimeout
( _ =>
( console.log("calling main() now...")
, main()
)
, 5000
)
// calling main() now...
// done
We wrote makePromise
to artificially delay the resolved value by two seconds (2000
milliseconds in the program).
What's critical to notice in this final program is that two seconds begins immediately. By the time we call Promise.all(...).then(...)
five seconds later, all of our Promises have already resolved a value. This is why we see "done"
immediately after main()
is called.