I am reading "Eloquent JavaScript" and at the end of Asynchronous chapter there is a section about execution gap in asynchronous operations and it shows an example. The example code below from the book is not runable as it uses some made up scenario.
function anyStorage(nest, source, name) {
if (source == nest.name) return storage(nest, name); else return routeRequest(nest, source, "storage", name);
}
async function chicks(nest, year) {
let list = "";
await Promise.all(network(nest).map(async name => {
list += `${name}: ${
await anyStorage(nest, name, `chicks in ${year}`)
}\n`; }));
return list;
}
It says the problem with this code, as I understand, is each asynchronous call e.g. anyStorage
will actually concatenate an empty list
and can't see the mutation from other asynchronous calls.
I tried to replicate this problem as below:
function delay(n) {
return Promise.resolve(setTimeout(()=>{}, n*1000));
}
async function asyncSum(a) {
let sum = 0;
await Promise.all(a.map(async i => sum += await delay(i)));
return sum;
}
asyncSum([1,2,3,4]).then(value => console.log(value));
But this works as expected. It prints the sum correctly. So did I misunderstand the book or there is something wrong with my example?