I/O
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, i);
}
// PUT THIS AT HIGHER SCOPE
// SO I CAN USE IT LATER
var myData;
// POPULATE `myData`
fs.readFile('/file.json', { encoding: 'utf8' }, function (err, data) {
if (err) {
return console.log('Oops...');
}
myData = JSON.parse(data);
});
// DO SOME OTHER STUFF THAT
// TAKES `n` AMOUNT OF TIME
// NOW USE `myData`
// (AND HOPE IT'S READY)
console.log(myData);
Thread / CPU
I/O
Worst Mail System Ever
zzz
Truck is waiting...
zzz
Truck is waiting...
zzz
Truck is waiting...
zzz
Truck is waiting...
zzz
Truck is waiting...
zzz
Truck is waiting...
& so on & so forth
Sledgehammer vs Fly
#1
#2
#1
#2
Trucks are waiting...
#1
#2
Trucks are waiting...
#1
#2
Trucks are waiting...
The IRL USPS
Truck Just Keeps on Truckin'
puts up flag
Truck returns the next day...
gives and receives new instructions
CPU & IO work in Async!
In computer science, asynchronous I/O, or non-blocking I/O is a form of input/output processing that permits other processing to continue before the transmission has finished.
like our neighbors
allowing the truck move on
Start the action and then wait for it to complete. Such an approach would block the progress of a program while the communication is in progress, leaving system resources idle.
zzz
When a program makes many I/O operations, this means that the processor can spend almost all of its time idle waiting for I/O operations to complete.
I/O operations on a computer can be extremely slow compared to the processing of data.
I/O device can incorporate mechanical devices that must physically move, such as a hard drive seeking a track to read or write; this is often orders of magnitude slower than the switching of electric current.
during a disk operation that takes ten milliseconds to perform, a processor that is clocked at one gigahertz could have performed ten million instruction-processing cycles.
and I/O often includes remote network request
for web-apps
event loop much faster ;-)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
You don't*. Async operations are built into the environment. You just leverage them.
Core Modules
Addons*
*Other's too, but these are standards based
var request = new XMLHttpRequest();
request.open('GET', '/my/api', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Geolocation
Wrapper around Events
Most of the Core APIs
window.addEventListener('click', e=>console.log(e));
navigator.geolocation.getCurrentPosition(doSomethingWithPosition);
function doSomethingWithPosition(position) {
/* position is an object like
position.coords.latitude,
position.coords.longitude
*/
console.log(position);
}
var fs = require('fs');
fs.readFile('/file.json', { encoding: 'utf8' }, function (err, data) {
if (err) {
return console.log('Oops...');
}
// do something with `JSON.parse(data)`
});
var request = new XMLHttpRequest();
request.open('GET', '/my/api', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Turn non-reusable, XHR code...
requestJSON('/my/api', function(err, data) {
if(err) {
// do something with error
}
// do something with data...
});
...into reusable API such as:
function requestJSON(url, cb) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
cb(null, data);
} else {
// We reached our target server, but it returned an error
cb("Error");
}
};
request.onerror = function() {
cb("Error");
// There was a connection error of some sort
};
request.send();
}
function getJSON(url) {
return fetch(url)
.then(ensureOK)
.then(toJSON)
.catch(handleAPIError);
function ensureOK(response) {
if(!response.ok) {
return Promise.reject(response);
}
return response;
}
function toJSON(response) {
return response.json();
}
function handleAPIError(response) {
// log and punt error
console.error('API Error Happened');
return Promise.reject(response);
}
}
function getJSON(url) {
return new Promise(function(resolve, reject){
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
resolve(JSON.parse(request.responseText));
} else {
reject(request.status);
}
};
request.onerror = function() {
reject("Baaad")
};
request.send();
});
}
async function requestJSON(url) {
try {
let response = await fetch(url);
if(!response.ok) {
throw "API Error Happened";
}
return response.json();
} catch(e) {
console.error(e);
throw e;
}
}
(async () => {
try {
let data = await requestJSON('/my/api');
console.log(data)
} catch(e) {
console.error(e);
}
})();