async() => { await }
Most of the internet is websites!
source: https://radar.cloudflare.comA client sends HTTP requests to a server. Servers send a response back.
Usually there are many clients.
One of the services I work on at Cloudflare handles 300,000+ requests per second.
Serving one client at a time doesn't scale, no matter how fast the server is.
Solution: serve multiple clients at once.
Operating system threads run at the same time.
JS is used a lot!
It would be nice to use it on the backend too.
Problem: JS doesn't have threads
Solution: concurrency using callbacks
In ~2010, async code looked like this ("callback hell")
fs.readdir(source, function (err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function (err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
})
Solution: async
/await
try {
let files = await fs.readdir;
for (let filename of files) {
console.log(filename)
let values = await gm(source + filename).size()
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(async function (width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
await this.resize(width, height).write(dest + 'w' + width + '_' + filename)
}.bind(this))
}
} catch(err) {
console.log('Error finding files: ' + err)
return;
}