Extracted from Chapter 11 of the book Eloquent Javascript, this code snippet showcases the use of Promises. You can interact with the code in a sandbox environment here.
I recently dabbled with the Promises
featured in this snippet and was surprised to find that the output was not in the expected order. Rather than seeing "1" followed by "2", the sequence was reversed. See below for the snippet and its corresponding output.
The function readStorage
is invoked first, preceding the execution of the Promise
. Given that readStorage
is a synchronous operation, I anticipated its output to be displayed prior to the callback within then
. However, it appears after the aforementioned callback's results.
Code:
import { bigOak } from "./crow-tech";
bigOak.readStorage("food caches", caches => {
caches.forEach(firstCache => {
bigOak.readStorage(firstCache, info => {
console.log("1:", info);
});
});
});
function storage(nest, name) {
return new Promise(resolve => {
nest.readStorage(name, result => resolve(result));
});
}
storage(bigOak, "enemies")
.then(value => console.log("2: Got", value));
Output:
2: Got ["Farmer Jacques' dog", "The butcher", …]
1: A hollow above the third big branch from the bottom. Several pieces of bread and a pile of acorns.
1: Buried below the patch of nettles (south side). A dead snake.
1: Middle of the hedge at Gilles' garden. Marked with a forked twig. Two bottles of beer.