It would help if ?promise explained that the function runs immediately, and why it does so. Otherwise, I have a feeling that many developers would put their slow code in promise() call, which sort of defeats the purpose of using promises.
Promises in Javascript work the same way, which surprised me again:
function f() {
console.log(0)
let p = new Promise((resolve, reject) => {
console.log(1)
resolve("Hi")
console.log(2)
});
console.log(3)
p.then((successMessage) => {
console.log("4");
});
}
f()
This follows a brief discussion that @jcheng5 and I had on the topic.
The following prints 0, 1, 2, 3, 4, which was surprising to me -- I expected 0, 3, 1, 2, 4.
It would help if
?promise
explained that the function runs immediately, and why it does so. Otherwise, I have a feeling that many developers would put their slow code inpromise()
call, which sort of defeats the purpose of using promises.Promises in Javascript work the same way, which surprised me again:
This answer on SO explains why JS promises work that way (though it's still not entirely clear in my mind): https://stackoverflow.com/a/31324439/412655