SlideShare a Scribd company logo
1 of 11
Código Assíncrono
JavaScript
O Ciclo de Eventos JavaScript
function maybe() {
console.log("…execute async, maybe?");
}
function proveIt() {
setTimeout(maybe, 0);
console.log("Hey, you just invoked me, and this is crazy…");
console.log("But I'll queue you up");
return "and you'll…";
}
proveIt();
Callbacks
function saveStuff(stuff, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://dev.jquery.com/~john/xdomain/test.php", true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
cb(null, xhr.responseText);
} else {
cb(error);
}
}
};
xhr.onerror = function (err) {
cb(err);
}
xhr.send(null);
}
saveStuff(stuff, function (err, data) {
if (err !== null) {
return err;
}
return data;
});
Callback Binding
saveStuff(stuff, function (err, data) {
this.do(err || data);
}).bind(doer);
Callback Binding
var allTheCustomerThings;
$("#getCustomer").click(function (cust) {
var id = $("#cust-id").val();
getCustomer(id, function (cust) {
allTheCustomerThings = cust;
getContacts(id, function (contacts) {
allTheCustomerThings.contacts = contacts;
getOrders(id, function (orders) {
allTheCustomerThings.orders = orders;
getAccountsRecv(id, function (ar) {
allTheCustomerThings.ar = ar;
// OK - we got all the data, NOW WHAT?! :-)
});
});
});
});
});
Promises
ArticleService.Save(art).then(function (art) {
alert(art);
}, function (err) {
alert(err);
});
Promises
Users.login(username, password)
.then(function () {
return usersModel.load();
})
.then(function () {
mobileApp.navigate('views/notesView.html');
})
.then(
null, // YAY! We made it!
function (err) {
showError(err.message);
}
);
Carregamento Assíncrono
<script async src="my.js">
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = '//third-party.com/resource.js';
s.parentNode.insertBefore(g, s);
}(document, 'script'));
Carregamento Assíncrono
<script async src="my.js">
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = '//third-party.com/resource.js';
s.parentNode.insertBefore(g, s);
}(document, 'script'));
Closures
for (var i = 0; i < coords.length; i++) {
(function(coords) {
mapquest.reverse({
key: config.mapquest.appKey,
coordinates: {
latitude: coords.lat,
longitude: coords.lng
}
}, function(err, location) {
// do something with location and coords
});
})(coords);
}
Perguntas?

More Related Content

What's hot

Java Thread Cronometro
Java Thread CronometroJava Thread Cronometro
Java Thread Cronometrojubacalo
 
Testes unitários de JS com Jasmine e Karma
Testes unitários de JS com Jasmine e KarmaTestes unitários de JS com Jasmine e Karma
Testes unitários de JS com Jasmine e KarmaDouglas Matoso
 
Progressive Mobile Web Apps
Progressive Mobile Web AppsProgressive Mobile Web Apps
Progressive Mobile Web Appsdynamis
 
Антон Полухин. C++17
Антон Полухин. C++17Антон Полухин. C++17
Антон Полухин. C++17Sergey Platonov
 
Lightning talk second
Lightning talk secondLightning talk second
Lightning talk secondShinUsuda
 
Фатальный недостаток Node.js
Фатальный недостаток Node.jsФатальный недостаток Node.js
Фатальный недостаток Node.jsOleksii Okhrymenko
 
Rambler.iOS #8: Чистые unit-тесты
Rambler.iOS #8: Чистые unit-тестыRambler.iOS #8: Чистые unit-тесты
Rambler.iOS #8: Чистые unit-тестыRAMBLER&Co
 
I will be callback/JS同步與非同步
I will be callback/JS同步與非同步I will be callback/JS同步與非同步
I will be callback/JS同步與非同步ZenChou2
 
Сборка JavaScript-проектов с помощью Grunt
Сборка JavaScript-проектов с помощью GruntСборка JavaScript-проектов с помощью Grunt
Сборка JavaScript-проектов с помощью GruntFDConf
 
Второй экрана для “Еды". Владимир Павликов. Kelnik. 29.01.2014
Второй экрана для “Еды". Владимир Павликов. Kelnik. 29.01.2014Второй экрана для “Еды". Владимир Павликов. Kelnik. 29.01.2014
Второй экрана для “Еды". Владимир Павликов. Kelnik. 29.01.2014SPECIA
 
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tipsOpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tipsHo Kim
 
JAVA Program in NetBeans
JAVA Program in NetBeansJAVA Program in NetBeans
JAVA Program in NetBeansHimanshiSingh71
 
Node.JS
Node.JSNode.JS
Node.JSeibaan
 
C++14 reflections
C++14 reflections C++14 reflections
C++14 reflections corehard_by
 
c ++ informe Nº5 ucsm
c ++ informe Nº5 ucsmc ++ informe Nº5 ucsm
c ++ informe Nº5 ucsmIsaac Aquino
 
Jav script xml-httprequest
Jav script   xml-httprequestJav script   xml-httprequest
Jav script xml-httprequestTed Hsu
 

What's hot (19)

Java Thread Cronometro
Java Thread CronometroJava Thread Cronometro
Java Thread Cronometro
 
Testes unitários de JS com Jasmine e Karma
Testes unitários de JS com Jasmine e KarmaTestes unitários de JS com Jasmine e Karma
Testes unitários de JS com Jasmine e Karma
 
Progressive Mobile Web Apps
Progressive Mobile Web AppsProgressive Mobile Web Apps
Progressive Mobile Web Apps
 
Антон Полухин. C++17
Антон Полухин. C++17Антон Полухин. C++17
Антон Полухин. C++17
 
Lightning talk second
Lightning talk secondLightning talk second
Lightning talk second
 
Фатальный недостаток Node.js
Фатальный недостаток Node.jsФатальный недостаток Node.js
Фатальный недостаток Node.js
 
Rambler.iOS #8: Чистые unit-тесты
Rambler.iOS #8: Чистые unit-тестыRambler.iOS #8: Чистые unit-тесты
Rambler.iOS #8: Чистые unit-тесты
 
Kruskal algorithm
Kruskal algorithmKruskal algorithm
Kruskal algorithm
 
I will be callback/JS同步與非同步
I will be callback/JS同步與非同步I will be callback/JS同步與非同步
I will be callback/JS同步與非同步
 
Сборка JavaScript-проектов с помощью Grunt
Сборка JavaScript-проектов с помощью GruntСборка JavaScript-проектов с помощью Grunt
Сборка JavaScript-проектов с помощью Grunt
 
Monads
MonadsMonads
Monads
 
Mikstura it2013
Mikstura it2013Mikstura it2013
Mikstura it2013
 
Второй экрана для “Еды". Владимир Павликов. Kelnik. 29.01.2014
Второй экрана для “Еды". Владимир Павликов. Kelnik. 29.01.2014Второй экрана для “Еды". Владимир Павликов. Kelnik. 29.01.2014
Второй экрана для “Еды". Владимир Павликов. Kelnik. 29.01.2014
 
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tipsOpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
OpenResty/Lua 70+ Advanced Programming Skills and Optimization tips
 
JAVA Program in NetBeans
JAVA Program in NetBeansJAVA Program in NetBeans
JAVA Program in NetBeans
 
Node.JS
Node.JSNode.JS
Node.JS
 
C++14 reflections
C++14 reflections C++14 reflections
C++14 reflections
 
c ++ informe Nº5 ucsm
c ++ informe Nº5 ucsmc ++ informe Nº5 ucsm
c ++ informe Nº5 ucsm
 
Jav script xml-httprequest
Jav script   xml-httprequestJav script   xml-httprequest
Jav script xml-httprequest
 

JavaScript Assíncrono

  • 2. O Ciclo de Eventos JavaScript function maybe() { console.log("…execute async, maybe?"); } function proveIt() { setTimeout(maybe, 0); console.log("Hey, you just invoked me, and this is crazy…"); console.log("But I'll queue you up"); return "and you'll…"; } proveIt();
  • 3. Callbacks function saveStuff(stuff, cb) { var xhr = new XMLHttpRequest(); xhr.open("GET", "http://dev.jquery.com/~john/xdomain/test.php", true); xhr.onreadystatechange = function(){ if ( xhr.readyState == 4 ) { if ( xhr.status == 200 ) { cb(null, xhr.responseText); } else { cb(error); } } }; xhr.onerror = function (err) { cb(err); } xhr.send(null); } saveStuff(stuff, function (err, data) { if (err !== null) { return err; } return data; });
  • 4. Callback Binding saveStuff(stuff, function (err, data) { this.do(err || data); }).bind(doer);
  • 5. Callback Binding var allTheCustomerThings; $("#getCustomer").click(function (cust) { var id = $("#cust-id").val(); getCustomer(id, function (cust) { allTheCustomerThings = cust; getContacts(id, function (contacts) { allTheCustomerThings.contacts = contacts; getOrders(id, function (orders) { allTheCustomerThings.orders = orders; getAccountsRecv(id, function (ar) { allTheCustomerThings.ar = ar; // OK - we got all the data, NOW WHAT?! :-) }); }); }); }); });
  • 7. Promises Users.login(username, password) .then(function () { return usersModel.load(); }) .then(function () { mobileApp.navigate('views/notesView.html'); }) .then( null, // YAY! We made it! function (err) { showError(err.message); } );
  • 8. Carregamento Assíncrono <script async src="my.js"> (function(d, t) { var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.src = '//third-party.com/resource.js'; s.parentNode.insertBefore(g, s); }(document, 'script'));
  • 9. Carregamento Assíncrono <script async src="my.js"> (function(d, t) { var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.src = '//third-party.com/resource.js'; s.parentNode.insertBefore(g, s); }(document, 'script'));
  • 10. Closures for (var i = 0; i < coords.length; i++) { (function(coords) { mapquest.reverse({ key: config.mapquest.appKey, coordinates: { latitude: coords.lat, longitude: coords.lng } }, function(err, location) { // do something with location and coords }); })(coords); }