JS Sophia - 14th March, 2019
const end = Date.now() + 5000;
while (Date.now() < end) {
// Expensive operation blocking the event loop
}
JSON.Parse
& JSON.stringify
app.get('/redos-me', (req, res) => {
let filePath = req.query.filePath;
// Nested quantifier, can be expensive !!!
if (fileName.match(/(\/.+)+$/)) {
console.log('valid path');
}
else {
console.log('invalid path');
}
res.sendStatus(200);
})
api.getUser(loggin, function(err, data) {
// ...
api.getGeoLocation(user, function(err, data) {
// ...
api.getWeather(location, function(err, data) {
// ...
api.notifyWeather(weather, function(err, data) {
// ...
});
});
});
});
api.getUser(loggin, function(err, data) {
// ...
api.getGeoLocation(user, function(err, data) {
// ...
api.getWeather(location, function(err, data) {
// ...
api.notifyWeather(weather, function(err, data) {
// ...
});
});
});
});
try{
api.getUser(loggin, function(err, data) {
// ...
api.getGeoLocation(user, function(err, data) {
// ...
api.getWeather(location, function(err, data) {
// ...
api.notifyWeather(weather, function(err, data) {
// ...
});
});
});
});
}
catch(err) {
// Async errors not catched here !!!
}
const successCallback = (data) => console.log(data);
const errorCallback = (error) => console.error(error);
async(source, successCallback, errorCallback);
async(source, function(err, data) {
// ...
});
function foo(x) {
// start doing something that could take a while
// make a `listener` event notification
// capability to return
return listener;
}
var evt = foo( 42 );
evt.on( "completion", function(){
// now we can do the next step!
} );
evt.on( "failure", function(err){
// oops, something went wrong in `foo(..)`
} );
function foo(promise) {
promise.then(function() {
// Code executed on promise fulfillment
},function() {
// Code executed on promise failure
});
}
promise.then(bar, errorBar);
then
method on it
// async(data, successCallback, errorCallback) function
function asyncPromisified(data) {
return new Promise(function(resolve, reject) {
async(data, resolve, reject);
});
}
// async(data, callback) "error-first" style
function asyncPromisified(data) {
return new Promise(function(resolve, reject) {
async(data, function(err,data) {
err ? reject(err) : resolve(data);
});
});
}
then
callback
registered will be called in order in the next microtask queue
executionthen
callbacks will be
called wether it is fulfilled or notundefined
// Success handler
function(v) {
return v;
}
// Error handler
function(err) {
throw err;
}
Promise.all([])
Promise.race([])
next()
methodvalue
propertydone
propertynext
method), the generator function executes until it encounters the
yield
keywordreturn
method on iterator to send the terminal signal