something ! }, 1000); require(['lodash', 'jquery'], ! function (_, $) {! // do something with lodash and jQuery! }! ); $('form').on('submit', function (e) {! // do something when user submit form! });! ! $('img').on('load', function (e) {! // do something when img loaded! });! ! $('img').on('error', function (e) {! // do something when img fails loading! }); $.ajax('/terms.json', function () {! // do something after api data ! // being loaded! }) Delay RequireJS AJAX DOM Events fs.readFile('foo.txt', function () {! // do something after foo.txt ! // being loaded! }) Node.js
something ! }, 1000); require(['lodash', 'jquery'], ! function (_, $) {! // do something with lodash and jQuery! }! ); $('form').on('submit', function () {! // do something when user submit form! });! ! $('img').on('load', function () {! // do something when img loaded! });! ! $('img').on('error', function () {! // do something when img fails loading! }); $.ajax('/terms.json', function () {! // do something after api data ! // being loaded! }) Delay RequireJS AJAX DOM Events fs.readFile('foo.txt', function () {! // do something after foo.txt ! // being loaded! }) Node.js
something ! }, 1000); require(['lodash', 'jquery'], ! function (_, $) {! // do something with lodash and jQuery! }! ); $('form').on('submit', function () {! // do something when user submit form! });! ! $('img').on('load', function () {! // do something when img loaded! });! ! $('img').on('error', function () {! // do something when img fails loading! }); $.ajax('/terms.json', function () {! // do something after api data ! // being loaded! }) Delay RequireJS AJAX DOM Events fs.readFile('foo.txt', function () {! // do something after foo.txt ! // being loaded! }) Node.js Nothing wrong with Callback Use it when your scenario is simple
callback) {! ! // Authorisation pass?! var url = '/api/authorize'; makeRequest(url, function (data, success) {! // (Omit) Callback if it fails… ! // Get user ID by name! url = '/api/getUserInfo/' + name + '?token=' + data.token;! makeRequest(url, function (data, success) {! // (Omit) Callback if it fails… ! // Get user's repo by user ID! url = '/api/getUserRepos?token=…&uid=' + data.uid;! makeRequest(url, function (data, success) {! // (Omit) Callback if it fails… ! // Finally success callback(data, true); });! });! });! }; API Authorisation Get User ID Get User Repos Token Token + User ID Callback Hell GitHubber#getUserRepos Question: How will you refactor it?
= null;! this.repos = [];! this.steps = ['_authorise', '_getUserInfo', '_getUserRepos'];! }! ! var proto = {! _authorise: function () {! var url = '/api/authorise';! makeRequest(url, function (data, success) {! this.token = data.token;! this.emit('success', [‘_authorise']);! });! },! _getUserInfo: function () {! var url = '/api/getUserInfo/' + this.name + '?token=' + data.token;! makeRequest(url, function (data, success) {! this.id = data.id;! this.emit('success', [‘_getUserInfo']);! });! },! _getUserRepos: function () {! var url = '/api/getRepos/?uid=' + this.id + ! '?token=' + data.token;! makeRequest(url, function (data, success) {! this.repos = data.repos;! this.emit('success', [‘_getUserRepos', this.repos]);! });! },! getUserRepos: function (callback) {! var that = this;! that.on('success', function (e, method) {! var offset = that.steps.indexOf(method);! if (offset !== that.steps.length - 1) { // Other steps! that[that.steps[offset + 1]];! } else { // _getUserRepos! callback(that.repos); ! }! });! that[that.steps[0]]();! }! }; My Solution Before understanding Promise • Break callbacks into methods with semantic naming • Exchange data with instance variables • Make use of custom events I am a big fan of Custom Events Wolfy87/EventEmitter Better but still not straightforward Need read carefully to understand the trick ex. sequence, error handling, and parallel events
{ ! ! ! }, “Our workers will do all tasks for you” “Keep the ticket for now. I promise you will get a fulfilled or rejected result” • Pending • Fulfilled: that.repoDeferred.resolve(data.repos) • Rejected: that.repoDeferred.reject(‘service unavailable’) that.repoDeferred = new $.Deferred(); that.asyncTasks() return that.repoDeferred.promise(); “This task may take a while”
straightforward way (.then) • Built-in error handling API (.fail) • Batch execute parallel tasks easily (Promise.all) Solved a lot of async design issues
tool for creating and composing asynchronous promises in JavaScript • RSVP.js A lightweight library that provides tools for organising asynchronous code • when.js A solid, fast Promises/A+ and when() implementation, plus other async goodies. • bluebird (most popular) Bluebird is a full featured promise library with unmatched performance.
tool for creating and composing asynchronous promises in JavaScript • RSVP.js A lightweight library that provides tools for organising asynchronous code • when.js A solid, fast Promises/A+ and when() implementation, plus other async goodies. • bluebird (most popular) Bluebird is a full featured promise library with unmatched performance. Currently you probably need library for polyfills Use jQuery Deferred with awareness