Why do we need promises? How does promises compare to a simple callback approach or modules like async? Are promises just a hype or a new standard for asynchronous code?
This talk was given at JSSummit 2013. Entitled "Avoiding Callback Hell with Async.js", my talk focused on common pitfalls with asynchronous functions and callbacks in JavaScript, and using the async.js library and its advanced control flows to create cleaner, more manageable code.
This document introduces JavaScript promises as a way to manage asynchronous code and avoid "callback hell". It explains that promises represent the eventual result of an asynchronous operation and allow restoring functional composition and error handling to asynchronous code. Code examples are provided to demonstrate how promises work by having asynchronous functions return promise objects instead of relying on callbacks. The differences between callbacks and promises are outlined, such as promises being objects that are returned rather than functions passed as arguments. It also addresses how to handle functions that don't natively return promises by wrapping them to return a promise instead. Finally, a callback hell example is provided and solved using promises to flatten the nested callbacks.
Many developers new to Node.js struggle with writing asynchronous code in a clean, concise, easy to maintain manner. There are many strategies for managing and preventing 'callback hell' in Node.js. We'll walk through many of those strategies, from Promises to Generators to flow control libraries, and show that with a bit of forethought, writing asynchronous code in Javascript and Node.js can be easy and maintainable.
This time it was the microcosm that brought us a few interesting bugs. We have checked the open-source project μManager with our analyzer PVS-Studio. This project is a software package for automated microscope image acquisition.
Rewrite few familiar Cocoa Touch code examples from Obj-C to Swift by learning to use Closures, Enums, Switch-Case with Pattern matching, Singleton, GCD, CoreGraphics.
Presented at Tel Aviv iOS Developers Meetup.
This document discusses asynchronous JavaScript and concurrency in JavaScript. It covers several key points:
- JavaScript uses an event loop model where callbacks are used to handle asynchronous operations like I/O instead of blocking. This allows JavaScript to remain single-threaded.
- The event loop processes the callback queue synchronously. When a callback finishes, the next message is processed. Timeouts like setTimeout allow callbacks to be delayed.
- Promises and the newer async/await syntax provide cleaner ways to handle asynchronous code compared to callbacks alone. Web Workers also allow running scripts in background threads.
- Technologies like AJAX and the Fetch API allow asynchronous HTTP requests from JavaScript. This enables asynchronous data fetching, which is
This document discusses the good, bad, and awful parts of JavaScript. It covers JavaScript functions, arrays, asynchronous JavaScript, and references. Key points include an overview of functions, including definition, augmenting, scope, arguments, apply/call, closure, curry and memoization. Arrays and important array methods like slice, splice and sort are explained. Asynchronous JavaScript discusses using async functions, sometimes-async functions, and throwing errors from callbacks. The bad parts section mentions issues like global variables, reserved words, and bitwise operators. References for further reading are also provided.
The evolution of java script asynchronous callsHuy Hoàng Phạm
The document summarizes the evolution of asynchronous calls in JavaScript, from callbacks to promises to async/await. It discusses how callbacks can lead to "callback hell" code that is difficult to read and maintain. Promises were introduced to make asynchronous code flatter and easier to read by chaining operations. Async/await was later added and allows asynchronous code to be written in a synchronous-looking way by using await in async functions. Overall, the document traces the progression from callbacks to promises to async/await in improving the handling of asynchronous operations in JavaScript.
This talk was given at JSSummit 2013. Entitled "Avoiding Callback Hell with Async.js", my talk focused on common pitfalls with asynchronous functions and callbacks in JavaScript, and using the async.js library and its advanced control flows to create cleaner, more manageable code.
This document introduces JavaScript promises as a way to manage asynchronous code and avoid "callback hell". It explains that promises represent the eventual result of an asynchronous operation and allow restoring functional composition and error handling to asynchronous code. Code examples are provided to demonstrate how promises work by having asynchronous functions return promise objects instead of relying on callbacks. The differences between callbacks and promises are outlined, such as promises being objects that are returned rather than functions passed as arguments. It also addresses how to handle functions that don't natively return promises by wrapping them to return a promise instead. Finally, a callback hell example is provided and solved using promises to flatten the nested callbacks.
Many developers new to Node.js struggle with writing asynchronous code in a clean, concise, easy to maintain manner. There are many strategies for managing and preventing 'callback hell' in Node.js. We'll walk through many of those strategies, from Promises to Generators to flow control libraries, and show that with a bit of forethought, writing asynchronous code in Javascript and Node.js can be easy and maintainable.
This time it was the microcosm that brought us a few interesting bugs. We have checked the open-source project μManager with our analyzer PVS-Studio. This project is a software package for automated microscope image acquisition.
Rewrite few familiar Cocoa Touch code examples from Obj-C to Swift by learning to use Closures, Enums, Switch-Case with Pattern matching, Singleton, GCD, CoreGraphics.
Presented at Tel Aviv iOS Developers Meetup.
This document discusses asynchronous JavaScript and concurrency in JavaScript. It covers several key points:
- JavaScript uses an event loop model where callbacks are used to handle asynchronous operations like I/O instead of blocking. This allows JavaScript to remain single-threaded.
- The event loop processes the callback queue synchronously. When a callback finishes, the next message is processed. Timeouts like setTimeout allow callbacks to be delayed.
- Promises and the newer async/await syntax provide cleaner ways to handle asynchronous code compared to callbacks alone. Web Workers also allow running scripts in background threads.
- Technologies like AJAX and the Fetch API allow asynchronous HTTP requests from JavaScript. This enables asynchronous data fetching, which is
This document discusses the good, bad, and awful parts of JavaScript. It covers JavaScript functions, arrays, asynchronous JavaScript, and references. Key points include an overview of functions, including definition, augmenting, scope, arguments, apply/call, closure, curry and memoization. Arrays and important array methods like slice, splice and sort are explained. Asynchronous JavaScript discusses using async functions, sometimes-async functions, and throwing errors from callbacks. The bad parts section mentions issues like global variables, reserved words, and bitwise operators. References for further reading are also provided.
The evolution of java script asynchronous callsHuy Hoàng Phạm
The document summarizes the evolution of asynchronous calls in JavaScript, from callbacks to promises to async/await. It discusses how callbacks can lead to "callback hell" code that is difficult to read and maintain. Promises were introduced to make asynchronous code flatter and easier to read by chaining operations. Async/await was later added and allows asynchronous code to be written in a synchronous-looking way by using await in async functions. Overall, the document traces the progression from callbacks to promises to async/await in improving the handling of asynchronous operations in JavaScript.
Functions being first-class citizens in JavaScript offers developers a tremendous amount power and
flexibilty. However, what good is all this power if you don't know how to harness it?
This talk will provide a thorough examination of JavaScript functions. Topics
that will be covered in this talk are:
* Functions are objects
* Execution Context and the Scope Chain
* Closures
* Modifying Context
* The Various Forms of Functions.
Attendees will leave this talk understanding the power of JavaScript functions and the knowledge to apply new
techiques that will make their JavaScript cleaner, leaner and more maintainable.
1) Promises are objects that represent the eventual completion (or failure) of an asynchronous operation, rather than using callbacks. They provide a cleaner way to handle asynchronous code than callbacks alone.
2) A promise has three possible states: pending, fulfilled, and rejected. Promises allow multiple handlers to be attached to an asynchronous operation via the .then() method. Handlers will be called even if attached after the promise is settled.
3) Common uses of promises include handling data retrieval from external sources, loading assets, and handling animations. Promises are well-suited for any potentially asynchronous operation.
As a guest speaker in NCU, I gave a talk about some best practices of JavaScript programming to college students. It covers basic JavaScript elements and some common pitfalls while dealing with asynchronous programming.
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...PVS-Studio
The first-person shooter 'Serious Sam' celebrated its release anniversary on March, 2016. In honor of this, the game developers form the Croatian company Croteam decided to open the source code for the game engine, Serious Engine 1 v.1.10. It provoked the interest of a large number of developers, who got an opportunity to have a look at the code and improve it. I have also decided to participate in the code improvement, and wrote an article reviewing the bugs that were found by PVS-Studio analyzer.
JavaScript Loop: Optimization of Weak TypingJanlay Wu
This document discusses JavaScript loop optimization and the difference in performance between i++ and i-- loops. It shows that i++ and i-- have similar performance in modern browsers. To better measure the performance, it defines test functions that run the loops 10,000 times with 1,000,000 iterations each. The results show minor differences between browsers but no clear winner between i++ and i--. It also discusses the differences between strong/weak and static/dynamic typing in JavaScript compared to languages like C/Java.
This document summarizes various control structures in C++ that allow programs to make decisions and repeat code. It describes conditional structures like if/else that execute code based on conditions. It also covers iteration structures like while, do-while, and for loops that repeat code. Additionally, it mentions jump statements like break, continue, goto that change the flow of loops. It provides examples to illustrate how each control structure works.
The document discusses loop statements in C++ including while loops, for loops, and examples of each. It covers using loops to print stair step patterns with asterisks of increasing lengths. It also assigns practice problems for students to design and code reverse stair step patterns and a diamond shape pattern using loops.
A Spin-off: Firebird Checked by PVS-StudioAndrey Karpov
We are currently working on a great task of carrying out a detailed comparison of four code analyzers: CppCat, Cppcheck, PVS-Studio and Visual Studio 2013 (i.e. its built-in code analyzer). As a set of materials to base this comparison on, we decided to check at least 10 open-source projects and study the reports from all the analyzers. This is a very labor-intensive task and it is not over yet. However, we have already checked a few projects and can share some of the results with you. And that's what I'm going to do in this article. We'll start with interesting bugs we have managed to find in Firebird with the help of PVS-Studio.
Futures allow asynchronous and non-blocking operations in Scala. They represent a value that may be available in the future. Promises allow producing values for futures - a promise can be used to complete a future with a value. Futures can be composed using methods like map, flatMap, and recover to build asynchronous workflows. Callbacks allow non-blocking handling of future results.
This document discusses JavaScript functions. It covers function definitions, invocation patterns, the this keyword, and function methods like call, apply, and bind. Function definitions can be declared using the function keyword or assigned anonymously. Functions are first-class citizens that can be passed around and returned. Invocation patterns include direct invocation, method invocation, constructor invocation, and reflective invocation using call and apply. The this keyword is determined by the invocation pattern and bind can be used to set the this value.
The document discusses CompletableFuture in Java. It begins with an introduction to java.util.Future and its limitations. It then discusses how CompletableFuture allows asynchronous and parallel operations through callbacks and chaining of tasks. This improves performance over serial execution. It provides examples of CompletableFuture methods like supplyAsync, thenApply, thenCombine, and allOf. Finally, it discusses how CompletableFuture can be used to build powerful and scalable libraries.
Using Akka futures
Akka Futures definition: A Future is a data structure used to retrieve of some concurrentoperationThis operation is performed by an Actor or a dispatcher directly result can be accessed synchronously or asynchronously.
A presentation of what are JavaScript Promises, what problems they solve and how to use them. Dissects some Bluebird features, the most complete Promise library available for NodeJS and browser.
Pro Java Fx – Developing Enterprise ApplicationsStephen Chin
This document summarizes Stephen Chin's presentation on Pro JavaFX - Developing Enterprise Applications. It discusses JFXtras layouts and controls, automated JavaFX testing, sample enterprise applications using JavaFX, and calling REST and SOAP services from JavaFX. It also advertises a JavaFXpert RIA exemplar challenge and provides information on learning JavaFX.
The document discusses using Exporter::Proxy to split up large Perl modules into smaller, more manageable chunks by functionality. It proposes splitting modules into "top-half" dispatcher modules that export symbols and dispatch calls to "bottom-half" modules that implement the specific functionality. This allows for a clean separation of interfaces from implementations and makes modules easier to maintain and extend over time.
The document discusses Rust's ownership system and borrowing. It explains that variables own the memory for their values, and when a variable goes out of scope that memory is returned. References allow borrowing values without transferring ownership. References must live shorter than the values they reference. Mutable references also allow changing borrowed values, but there can only be one mutable reference at a time.
What is Delegate?
What is Asynchronous Delegate?
BeginInvoke() method
EndInvoke() method
IAsyncResult Interface
AsyncCallback Delegate
Ways to call methods asynchronously using BeginInvoke() and EndInvoke()
This document discusses code generation with Java compiler plugins. It provides examples of using annotations like @Getter and @RequiredArgsConstructor to remove boilerplate code. It then compares annotation processing and javac plugins, explaining that javac plugins can access and manipulate abstract syntax trees during compilation. Finally, it outlines the basic steps to create a javac plugin, including implementing the Plugin interface and creating a provider configuration file.
II Konferencja Naukowa : Nauka o informacji (informacja naukowa) w okresie zmian, Warszawa, 15-16.04.2013 r. Instytut Informacji Naukowej i Studiów Bibliologicznych, Uniwersytet Warszawski
The 2nd Scientific Conference : Information Science in an Age of Change, April 15-16, 2013. Institute of Information and Book Studies, University of Warsaw
Functions being first-class citizens in JavaScript offers developers a tremendous amount power and
flexibilty. However, what good is all this power if you don't know how to harness it?
This talk will provide a thorough examination of JavaScript functions. Topics
that will be covered in this talk are:
* Functions are objects
* Execution Context and the Scope Chain
* Closures
* Modifying Context
* The Various Forms of Functions.
Attendees will leave this talk understanding the power of JavaScript functions and the knowledge to apply new
techiques that will make their JavaScript cleaner, leaner and more maintainable.
1) Promises are objects that represent the eventual completion (or failure) of an asynchronous operation, rather than using callbacks. They provide a cleaner way to handle asynchronous code than callbacks alone.
2) A promise has three possible states: pending, fulfilled, and rejected. Promises allow multiple handlers to be attached to an asynchronous operation via the .then() method. Handlers will be called even if attached after the promise is settled.
3) Common uses of promises include handling data retrieval from external sources, loading assets, and handling animations. Promises are well-suited for any potentially asynchronous operation.
As a guest speaker in NCU, I gave a talk about some best practices of JavaScript programming to college students. It covers basic JavaScript elements and some common pitfalls while dealing with asynchronous programming.
Serious Sam shooter anniversary - finding bugs in the code of the Serious Eng...PVS-Studio
The first-person shooter 'Serious Sam' celebrated its release anniversary on March, 2016. In honor of this, the game developers form the Croatian company Croteam decided to open the source code for the game engine, Serious Engine 1 v.1.10. It provoked the interest of a large number of developers, who got an opportunity to have a look at the code and improve it. I have also decided to participate in the code improvement, and wrote an article reviewing the bugs that were found by PVS-Studio analyzer.
JavaScript Loop: Optimization of Weak TypingJanlay Wu
This document discusses JavaScript loop optimization and the difference in performance between i++ and i-- loops. It shows that i++ and i-- have similar performance in modern browsers. To better measure the performance, it defines test functions that run the loops 10,000 times with 1,000,000 iterations each. The results show minor differences between browsers but no clear winner between i++ and i--. It also discusses the differences between strong/weak and static/dynamic typing in JavaScript compared to languages like C/Java.
This document summarizes various control structures in C++ that allow programs to make decisions and repeat code. It describes conditional structures like if/else that execute code based on conditions. It also covers iteration structures like while, do-while, and for loops that repeat code. Additionally, it mentions jump statements like break, continue, goto that change the flow of loops. It provides examples to illustrate how each control structure works.
The document discusses loop statements in C++ including while loops, for loops, and examples of each. It covers using loops to print stair step patterns with asterisks of increasing lengths. It also assigns practice problems for students to design and code reverse stair step patterns and a diamond shape pattern using loops.
A Spin-off: Firebird Checked by PVS-StudioAndrey Karpov
We are currently working on a great task of carrying out a detailed comparison of four code analyzers: CppCat, Cppcheck, PVS-Studio and Visual Studio 2013 (i.e. its built-in code analyzer). As a set of materials to base this comparison on, we decided to check at least 10 open-source projects and study the reports from all the analyzers. This is a very labor-intensive task and it is not over yet. However, we have already checked a few projects and can share some of the results with you. And that's what I'm going to do in this article. We'll start with interesting bugs we have managed to find in Firebird with the help of PVS-Studio.
Futures allow asynchronous and non-blocking operations in Scala. They represent a value that may be available in the future. Promises allow producing values for futures - a promise can be used to complete a future with a value. Futures can be composed using methods like map, flatMap, and recover to build asynchronous workflows. Callbacks allow non-blocking handling of future results.
This document discusses JavaScript functions. It covers function definitions, invocation patterns, the this keyword, and function methods like call, apply, and bind. Function definitions can be declared using the function keyword or assigned anonymously. Functions are first-class citizens that can be passed around and returned. Invocation patterns include direct invocation, method invocation, constructor invocation, and reflective invocation using call and apply. The this keyword is determined by the invocation pattern and bind can be used to set the this value.
The document discusses CompletableFuture in Java. It begins with an introduction to java.util.Future and its limitations. It then discusses how CompletableFuture allows asynchronous and parallel operations through callbacks and chaining of tasks. This improves performance over serial execution. It provides examples of CompletableFuture methods like supplyAsync, thenApply, thenCombine, and allOf. Finally, it discusses how CompletableFuture can be used to build powerful and scalable libraries.
Using Akka futures
Akka Futures definition: A Future is a data structure used to retrieve of some concurrentoperationThis operation is performed by an Actor or a dispatcher directly result can be accessed synchronously or asynchronously.
A presentation of what are JavaScript Promises, what problems they solve and how to use them. Dissects some Bluebird features, the most complete Promise library available for NodeJS and browser.
Pro Java Fx – Developing Enterprise ApplicationsStephen Chin
This document summarizes Stephen Chin's presentation on Pro JavaFX - Developing Enterprise Applications. It discusses JFXtras layouts and controls, automated JavaFX testing, sample enterprise applications using JavaFX, and calling REST and SOAP services from JavaFX. It also advertises a JavaFXpert RIA exemplar challenge and provides information on learning JavaFX.
The document discusses using Exporter::Proxy to split up large Perl modules into smaller, more manageable chunks by functionality. It proposes splitting modules into "top-half" dispatcher modules that export symbols and dispatch calls to "bottom-half" modules that implement the specific functionality. This allows for a clean separation of interfaces from implementations and makes modules easier to maintain and extend over time.
The document discusses Rust's ownership system and borrowing. It explains that variables own the memory for their values, and when a variable goes out of scope that memory is returned. References allow borrowing values without transferring ownership. References must live shorter than the values they reference. Mutable references also allow changing borrowed values, but there can only be one mutable reference at a time.
What is Delegate?
What is Asynchronous Delegate?
BeginInvoke() method
EndInvoke() method
IAsyncResult Interface
AsyncCallback Delegate
Ways to call methods asynchronously using BeginInvoke() and EndInvoke()
This document discusses code generation with Java compiler plugins. It provides examples of using annotations like @Getter and @RequiredArgsConstructor to remove boilerplate code. It then compares annotation processing and javac plugins, explaining that javac plugins can access and manipulate abstract syntax trees during compilation. Finally, it outlines the basic steps to create a javac plugin, including implementing the Plugin interface and creating a provider configuration file.
II Konferencja Naukowa : Nauka o informacji (informacja naukowa) w okresie zmian, Warszawa, 15-16.04.2013 r. Instytut Informacji Naukowej i Studiów Bibliologicznych, Uniwersytet Warszawski
The 2nd Scientific Conference : Information Science in an Age of Change, April 15-16, 2013. Institute of Information and Book Studies, University of Warsaw
This document discusses various accounting concepts related to companies:
1. It defines a company as an artificial entity established through legal processes to undertake business ventures, with shareholders as owners.
2. It explains different types of share capital such as authorized, issued, subscribed, called-up, and paid-up capital.
3. It describes the two ways companies can issue shares - for cash or consideration other than cash, and provides the accounting entries for issuing shares for cash whether payable in lump sum or installments.
Paragraf pertama menjelaskan tim ICT Universitas Multimedia Nusantara berhasil menjadi juara pertama dalam kompetisi programming CompFest UI 2013 dengan mengalahkan ratusan peserta lainnya. Tim ALPHA UMN yang terdiri dari tiga orang mahasiswa berhasil mendapatkan juara satu dalam kategori Senior Competitive programming. Kompetisi ini merupakan kontes programming tingkat nasional.
This document provides step-by-step instructions for setting up and using Google Calendar. It explains how to sign in to Google Calendar using a Gmail account, set preferences like language and time zone, and create events, reminders, and tasks. Key aspects covered include how to create a monthly calendar to track obligations, set repeating monthly reminders, and use the tasks function within Google Calendar to organize tasks and mark them as complete.
1. Humidification is important to provide moisture to inspired gas as the upper airway normally humidifies and warms air. Dry gas can damage the respiratory tract.
2. Various types of humidifiers include bubble, passover, and heated humidifiers. Heat and moisture exchangers are passive humidifiers that recycle heat and moisture from expired gas.
3. Factors like temperature, surface area, and contact time impact humidifier performance. Clinical signs of inadequate humidity include thick secretions and increased work of breathing. Humidification is indicated when the upper airway is bypassed.
El documento proporciona información sobre el diseño de un trono para el villano Dr. Facilier de la película La princesa y el Sapo. El trono tendrá una estructura de hierro y cobre con detalles como esferas, calaveras y plumas. Se presentan dimensiones, materiales, vistas en planta y detalles para su construcción.
Este documento proporciona información sobre las maderas y productos de madera disponibles en Madesol S.A. Incluye detalles sobre 15 tipos de madera como Jatoba, Ipe, Cedro y Caoba, así como sus usos, disponibilidad y precios. También describe productos como plywood, MDF hidrofugo y sus especificaciones técnicas. El objetivo es informar a los clientes sobre las opciones de madera y productos relacionados que ofrece la compañía.
El documento describe el diseño de un ottoman llamado "Mahi" en el estilo bohemio. El ottoman tiene una forma redonda y vivos colores para representar el alma libre y la alegría del estilo bohemio. Está hecho de seda bordada para el tapizado y rattan para la base y patas, y mide 40 cm de altura para sentarse o apoyar los pies.
Este documento describe un mueble multifuncional diseñado para una actriz. El mueble divide el área de estar y dormitorio de un loft y cuenta con espacios para televisión, escritorio, estanterías, closet y coqueta. Está hecho de madera caoba africana y aglomerado de madera con colores llamativos que representan la cultura africana. El mueble es funcional, estético y dinámico para satisfacer las necesidades de la actriz.
G-Dragon es un rapero y cantante surcoreano de 28 años conocido como líder de la banda de K-pop Big Bang. Comenzó su carrera a los 5 años y debutó oficialmente en 2006 con Big Bang, que sigue siendo uno de los grupos más exitosos de Corea del Sur. Además de su música, G-Dragon también es reconocido como un icono de la moda y un empresario exitoso.
Este documento describe un mueble diseñado para Emma Watson. El mueble tiene un estilo simple y elegante con detalles que representan la carrera y personalidad de Watson, como la madera de roble en referencia a Harry Potter. El mueble está dividido en zonas para sala y habitación, con estantes, nichos y compartimentos para almacenar libros, premios, ropa y objetos personales de Watson.
El documento describe el estilo de diseño escandinavo u nórdico, caracterizado por la funcionalidad, el uso de la madera, y la sencillez. Los principales elementos del estilo incluyen la madera, el cuero, colores neutros como gris y beige, y muebles bajos con líneas rectas. El documento también proporciona detalles sobre los materiales y dimensiones de un otomano de diseño nórdico.
Elmer figueroa arce alias chayanne presentacionpaolatezanos
El documento proporciona información biográfica y personal sobre el cantante puertorriqueño Chayanne. Detalla sus logros musicales, sus películas y giras. También describe su personalidad como enérgica, simpática y humilde. Además, presenta planes para un mueble multifuncional dividido en áreas de sala y dormitorio que refleja los gustos musicales de Chayanne.
Asynchronous programming done right - Node.jsPiotr Pelczar
This document discusses asynchronous programming and avoiding race conditions. It covers how asynchronous actions allow the main program flow to continue processing without blocking on I/O. It also discusses how asynchronous programming works with callbacks and promises rather than sequential execution. It provides examples of using libraries like Async to control asynchronous flows and common pitfalls to avoid like double callbacks and unexpected asynchronous behavior.
Asynchronous JavaScript development allows long-running operations like network requests or file access to occur without blocking the main thread through an event-driven programming model and callback functions. The browser uses an event loop to queue and execute events. While JavaScript can only execute one task at a time, asynchronous functions expose callbacks to handle completed operations. This can lead to "callback hell" where code becomes nested and difficult to follow. Promises and async/await were introduced to simplify asynchronous code by handling callbacks in a cleaner way similar to synchronous code. Web workers also allow true concurrency by running scripts on a separate thread.
The document discusses various methods from the async module in Node.js for controlling asynchronous callback flow, including:
1) Executing tasks in series or parallel, cascading tasks together, queuing tasks with concurrency control, iterating over arrays, mapping arrays, and reducing arrays.
2) Additional methods for filtering arrays based on an async truth test, and detecting the first value in an array that passes an async truth test.
3) Examples are provided for each method demonstrating how to use the async module to control asynchronous control flow in Node.js applications.
Avoiding callback hell in Node js using promisesAnkit Agarwal
This document discusses using promises in Node.js to avoid callback hell. It explains that Node.js is event-based and non-blocking, allowing it to handle multiple requests simultaneously. However, nested callbacks can result in unwieldy callback pyramids or "callback hell". Promises provide a way to write asynchronous code in a more linear way using method chaining. Key benefits include separation of concerns between wrapping asynchronous functions and controlling flow, as well as more readable code. The document provides examples of chaining, nesting, combining, and creating promises using deferred objects in the Q promise library.
This document discusses promises and asynchronous programming in Node.js. It begins with an overview of promises and their advantages over callbacks for handling asynchronous code. It then covers the Node.js event loop model and how promises work, including their states, creation, combination, and error handling. Advanced promise usage patterns like promisification, nodeification, and resolution are also summarized.
This document discusses the problems with asynchronous JavaScript and callbacks, and introduces promises as a better abstraction. It explains that promises represent asynchronous values, and allow asynchronous code to be written in a more synchronous and readable way using chained .then() calls. It provides examples of how common asynchronous patterns like error handling, parallel operations, and transforming return values can be implemented cleanly with promises. Finally, it discusses popular promise libraries and the upcoming native ES6 Promise implementation.
Promises are so passé - Tim Perry - Codemotion Milan 2016Codemotion
The document discusses asynchronous programming in JavaScript and how it has evolved over time. It covers callbacks, promises, generators, and the new async/await syntax. Callbacks were difficult to read and handle errors across steps. Promises provided a better model but still had ceremony and didn't play nicely with other constructs. Generators allowed writing async code that looked synchronous but required wrapping in a promise. Async/await builds on promises and generators by providing syntax that looks like synchronous code while still being asynchronous under the hood. It addresses issues with previous approaches but developers still need to handle errors and can overuse await. Async/await is available in modern browsers and makes asynchronous JavaScript much cleaner.
Promises are a popular pattern for asynchronous operations in JavaScript, existing in some form in every client-side framework in widespread use today. We'll give a conceptual and practical intro to promises in general, before moving on to talking about how they fit into Angular. If you've ever wondered what exactly $q was about, this is the place to learn!
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
This presentation is about JavaScript Promise. Topics covered in this session are:
1. Asynchronous processing in JavaScript
2. Callbacks and Callback hell
3. Promises arrive in JavaScript!
4. Constructing a Promise
5. Promise states
6. Promises chaining and transformation
7. Error handling
8. Promise.all() and Promise.race()
This document provides an overview of various JavaScript concepts and techniques, including:
- Prototypal inheritance allows objects in JavaScript to inherit properties from other objects. Functions can act as objects and have a prototype property for inheritance.
- Asynchronous code execution in JavaScript is event-driven. Callbacks are assigned as event handlers to execute code when an event occurs.
- Scope and closures - variables are scoped to functions. Functions create closures where they have access to variables declared in their parent functions.
- Optimization techniques like event delegation and requestAnimationFrame can improve performance of event handlers and animations.
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24Joachim Bengtsson
Nevyn Bengtsson (of Lookback, previously Spotify) presents his take on Futures/Promises/Tasks in Swift, and the problems with not abstracting asychronous code.
Code: https://github.com/nevyn/SPAsync/blob/master/Swift/main.swift
Blog: http://overooped.com/post/41803252527/methods-of-concurrency
Transcript: https://raw.githubusercontent.com/nevyn/SPAsync/master/Meta/SLUG%20Lightning%202015%20notes.txt
Async History
1. Callback - The past
2. Promise - The present
3. Async/Await - The future
The ppt is from the JavaScript meetup on 15th April 2017 at JSbot, Surat.
The document summarizes the key features of ES6 (ECMAScript 2015), the next version of JavaScript. It discusses new features like block scoping with let and const, arrow functions, classes, enhanced object literals, template strings, and promises. It also covers iterators and generators, which allow iterable objects to be looped over and asynchronous code to be written more cleanly. The presentation provides examples to illustrate how developers can take advantage of these new language features in their code.
Top questions with answers and code examples for JavaScript
JavaScript interview questions with answers:
What is closure in JavaScript and how does it work?
Answer: Closure is a feature in JavaScript where a function has access to its outer scope even after the outer function has returned. It is created when a function is defined inside another function, and the inner function retains access to the variables in the outer function’s scope. How do you declare a variable in JavaScript?
Answer: Variables in JavaScript can be declared using the “var”, “let” or “const” keywords. The “var” keyword is used to declare a variable with function scope, while “let” and “const” are used to declare variables with block scope.
The document provides an overview of JavaScript fundamentals, common patterns, and an introduction to Node.js. It discusses JavaScript data types and operators, variable scoping, objects and classes. It also covers jQuery optimization techniques like selector caching and event handling. For Node.js, it demonstrates how to create an HTTP server, manage dependencies with npm, build an Express server, and use middleware.
This document discusses using Redux-Saga for managing asynchronous logic in React/Redux applications. It introduces Redux-Saga as a runtime for generator functions that are used to handle asynchronous operations. Redux-Saga provides helpers for common tasks like waiting for actions and integrating with external APIs. It also allows for communication between sagas using channels. The document provides examples of generator functions and how Redux-Saga works with them to provide asynchronous behavior.
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2016.
http://www.ivanomalavolta.com
Similar to Promises - Asynchronous Control Flow (20)
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
Main news related to the CCS TSI 2023 (2023/1695)Jakub Marek
An English 🇬🇧 translation of a presentation to the speech I gave about the main changes brought by CCS TSI 2023 at the biggest Czech conference on Communications and signalling systems on Railways, which was held in Clarion Hotel Olomouc from 7th to 9th November 2023 (konferenceszt.cz). Attended by around 500 participants and 200 on-line followers.
The original Czech 🇨🇿 version of the presentation can be found here: https://www.slideshare.net/slideshow/hlavni-novinky-souvisejici-s-ccs-tsi-2023-2023-1695/269688092 .
The videorecording (in Czech) from the presentation is available here: https://youtu.be/WzjJWm4IyPk?si=SImb06tuXGb30BEH .
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/temporal-event-neural-networks-a-more-efficient-alternative-to-the-transformer-a-presentation-from-brainchip/
Chris Jones, Director of Product Management at BrainChip , presents the “Temporal Event Neural Networks: A More Efficient Alternative to the Transformer” tutorial at the May 2024 Embedded Vision Summit.
The expansion of AI services necessitates enhanced computational capabilities on edge devices. Temporal Event Neural Networks (TENNs), developed by BrainChip, represent a novel and highly efficient state-space network. TENNs demonstrate exceptional proficiency in handling multi-dimensional streaming data, facilitating advancements in object detection, action recognition, speech enhancement and language model/sequence generation. Through the utilization of polynomial-based continuous convolutions, TENNs streamline models, expedite training processes and significantly diminish memory requirements, achieving notable reductions of up to 50x in parameters and 5,000x in energy consumption compared to prevailing methodologies like transformers.
Integration with BrainChip’s Akida neuromorphic hardware IP further enhances TENNs’ capabilities, enabling the realization of highly capable, portable and passively cooled edge devices. This presentation delves into the technical innovations underlying TENNs, presents real-world benchmarks, and elucidates how this cutting-edge approach is positioned to revolutionize edge AI across diverse applications.
Your One-Stop Shop for Python Success: Top 10 US Python Development Providersakankshawande
Simplify your search for a reliable Python development partner! This list presents the top 10 trusted US providers offering comprehensive Python development services, ensuring your project's success from conception to completion.
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframePrecisely
Inconsistent user experience and siloed data, high costs, and changing customer expectations – Citizens Bank was experiencing these challenges while it was attempting to deliver a superior digital banking experience for its clients. Its core banking applications run on the mainframe and Citizens was using legacy utilities to get the critical mainframe data to feed customer-facing channels, like call centers, web, and mobile. Ultimately, this led to higher operating costs (MIPS), delayed response times, and longer time to market.
Ever-changing customer expectations demand more modern digital experiences, and the bank needed to find a solution that could provide real-time data to its customer channels with low latency and operating costs. Join this session to learn how Citizens is leveraging Precisely to replicate mainframe data to its customer channels and deliver on their “modern digital bank” experiences.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
Digital Marketing Trends in 2024 | Guide for Staying AheadWask
https://www.wask.co/ebooks/digital-marketing-trends-in-2024
Feeling lost in the digital marketing whirlwind of 2024? Technology is changing, consumer habits are evolving, and staying ahead of the curve feels like a never-ending pursuit. This e-book is your compass. Dive into actionable insights to handle the complexities of modern marketing. From hyper-personalization to the power of user-generated content, learn how to build long-term relationships with your audience and unlock the secrets to success in the ever-shifting digital landscape.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
Building Production Ready Search Pipelines with Spark and MilvusZilliz
Spark is the widely used ETL tool for processing, indexing and ingesting data to serving stack for search. Milvus is the production-ready open-source vector database. In this talk we will show how to use Spark to process unstructured data to extract vector representations, and push the vectors to Milvus vector database for search serving.
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Tatiana Kojar
Skybuffer AI, built on the robust SAP Business Technology Platform (SAP BTP), is the latest and most advanced version of our AI development, reaffirming our commitment to delivering top-tier AI solutions. Skybuffer AI harnesses all the innovative capabilities of the SAP BTP in the AI domain, from Conversational AI to cutting-edge Generative AI and Retrieval-Augmented Generation (RAG). It also helps SAP customers safeguard their investments into SAP Conversational AI and ensure a seamless, one-click transition to SAP Business AI.
With Skybuffer AI, various AI models can be integrated into a single communication channel such as Microsoft Teams. This integration empowers business users with insights drawn from SAP backend systems, enterprise documents, and the expansive knowledge of Generative AI. And the best part of it is that it is all managed through our intuitive no-code Action Server interface, requiring no extensive coding knowledge and making the advanced AI accessible to more users.
5th LF Energy Power Grid Model Meet-up SlidesDanBrown980551
5th Power Grid Model Meet-up
It is with great pleasure that we extend to you an invitation to the 5th Power Grid Model Meet-up, scheduled for 6th June 2024. This event will adopt a hybrid format, allowing participants to join us either through an online Mircosoft Teams session or in person at TU/e located at Den Dolech 2, Eindhoven, Netherlands. The meet-up will be hosted by Eindhoven University of Technology (TU/e), a research university specializing in engineering science & technology.
Power Grid Model
The global energy transition is placing new and unprecedented demands on Distribution System Operators (DSOs). Alongside upgrades to grid capacity, processes such as digitization, capacity optimization, and congestion management are becoming vital for delivering reliable services.
Power Grid Model is an open source project from Linux Foundation Energy and provides a calculation engine that is increasingly essential for DSOs. It offers a standards-based foundation enabling real-time power systems analysis, simulations of electrical power grids, and sophisticated what-if analysis. In addition, it enables in-depth studies and analysis of the electrical power grid’s behavior and performance. This comprehensive model incorporates essential factors such as power generation capacity, electrical losses, voltage levels, power flows, and system stability.
Power Grid Model is currently being applied in a wide variety of use cases, including grid planning, expansion, reliability, and congestion studies. It can also help in analyzing the impact of renewable energy integration, assessing the effects of disturbances or faults, and developing strategies for grid control and optimization.
What to expect
For the upcoming meetup we are organizing, we have an exciting lineup of activities planned:
-Insightful presentations covering two practical applications of the Power Grid Model.
-An update on the latest advancements in Power Grid -Model technology during the first and second quarters of 2024.
-An interactive brainstorming session to discuss and propose new feature requests.
-An opportunity to connect with fellow Power Grid Model enthusiasts and users.
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...Alex Pruden
Folding is a recent technique for building efficient recursive SNARKs. Several elegant folding protocols have been proposed, such as Nova, Supernova, Hypernova, Protostar, and others. However, all of them rely on an additively homomorphic commitment scheme based on discrete log, and are therefore not post-quantum secure. In this work we present LatticeFold, the first lattice-based folding protocol based on the Module SIS problem. This folding protocol naturally leads to an efficient recursive lattice-based SNARK and an efficient PCD scheme. LatticeFold supports folding low-degree relations, such as R1CS, as well as high-degree relations, such as CCS. The key challenge is to construct a secure folding protocol that works with the Ajtai commitment scheme. The difficulty, is ensuring that extracted witnesses are low norm through many rounds of folding. We present a novel technique using the sumcheck protocol to ensure that extracted witnesses are always low norm no matter how many rounds of folding are used. Our evaluation of the final proof system suggests that it is as performant as Hypernova, while providing post-quantum security.
Paper Link: https://eprint.iacr.org/2024/257
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3Data Hops
Free A4 downloadable and printable Cyber Security, Social Engineering Safety and security Training Posters . Promote security awareness in the home or workplace. Lock them Out From training providers datahops.com
Introduction of Cybersecurity with OSS at Code Europe 2024Hiroshi SHIBATA
I develop the Ruby programming language, RubyGems, and Bundler, which are package managers for Ruby. Today, I will introduce how to enhance the security of your application using open-source software (OSS) examples from Ruby and RubyGems.
The first topic is CVE (Common Vulnerabilities and Exposures). I have published CVEs many times. But what exactly is a CVE? I'll provide a basic understanding of CVEs and explain how to detect and handle vulnerabilities in OSS.
Next, let's discuss package managers. Package managers play a critical role in the OSS ecosystem. I'll explain how to manage library dependencies in your application.
I'll share insights into how the Ruby and RubyGems core team works to keep our ecosystem safe. By the end of this talk, you'll have a better understanding of how to safeguard your code.
Taking AI to the Next Level in Manufacturing.pdfssuserfac0301
Read Taking AI to the Next Level in Manufacturing to gain insights on AI adoption in the manufacturing industry, such as:
1. How quickly AI is being implemented in manufacturing.
2. Which barriers stand in the way of AI adoption.
3. How data quality and governance form the backbone of AI.
4. Organizational processes and structures that may inhibit effective AI adoption.
6. Ideas and approaches to help build your organization's AI strategy.
3. The problem
Q: How to control the asynchronous flow of your
application when there are dependencies between
two steps?
A: I can use Callbacks :)
function asyncFunction1(function (err, result) {
// do something here...
asyncFuncion2(function (err2, result2) {
// other stuff here...
})
})
4. However… Callbacks can get ugly
module.exports.verifyPassword = function(user, password, done) {
if(typeof password !== ‘string’) {
done(new Error(‘password should be a string’))
}
computeHash(password, user.passwordHashOpts, function(err, hash) {
if(err) {
done(err)
}
done(null, hash === user.passwordHash)
})
}
Callback being called multiple times
5. This one is easily fixed though...
module.exports.verifyPassword = function(user, password, done) {
if(typeof password !== ‘string’) {
return done(new Error(‘password should be a string’))
}
computeHash(password, user.passwordHashOpts, function(err, hash) {
if(err) {
return done(err)
}
return done(null, hash === user.passwordHash)
})
}
Always return when calling the callback
6. Q: How execute asynchronous function in
parallel and proceed when all have finished?
But what about parallel execution?
var finished = [false, false]
function asyncFunction1(function (err, result) {
// do some stuff
finished[0] = true
if (finished[0] === true && finished[1] === true) {
// proceed…
}
})
function asyncFunction2(function (err, result) {
// do some other stuff
finished[1] = true
if (finished[0] === true && finished[1] === true) {
// proceed…
}
})
9. The good ol’ async¹ module
async.waterfall([
function(callback) {
callback(null, 'one', 'two');
},
function(arg1, arg2, callback) {
// arg1 = 'one' and arg2 = 'two'
callback(null, 'three');
},
function(arg1, callback) {
// arg1 = 'three'
callback(null, 'done');
}
], function (err, result) {
// result now equals 'done'
});
async.parallel([
function(callback){
setTimeout(function(){
callback(null, 'one');
}, 200);
},
function(callback){
setTimeout(function(){
callback(null, 'two');
}, 100);
}
],
// optional callback
function(err, results){
// the results array will equal ['one','two']
even though
// the second function had a shorter timeout.
});
¹ https://github.com/caolan/async
10. But it can get cumbersome too...
What if I need to pass an argument to the first
function in the waterfall?
async.waterfall([
async.apply(myFirstFunction, 'zero'),
mySecondFunction,
myLastFunction,
], function (err, result) {
// result = 'done'
});
function myFirstFunction(arg1, callback) {
// arg1 now equals 'zero'
callback(null, 'one', 'two');
}
function mySecondFunction(arg1, arg2, callback) {
// arg1 = 'one' and arg2 = 'two'
callback(null, 'three');
}
function myLastFunction(arg1, callback) {
// arg1 = 'three'
callback(null, 'done');
}
11. DRY*
Error handling can be tiresome…
You have to bubble your errors up in every layer of
code you have.
And if you forget doing so, a wild bug may appear...
* Don’t Repeat Yourserlf
async.waterfall([
function(callback) {
doSomething(function(err, result){
if (err) return callback(err)
callback(null, result, 'another-thing');
})
},
function(arg1, arg2, callback) {
doAnotherStuff(function(err, result){
if (err) return callback(err)
callback(null, result);
})
},
function(arg1, callback) {
doAnotherStuff(function(err, result){
if (err) return callback(err)
callback(null, result);
})
}
], function (err, result) {
// result now equals 'done'
});
Bug used “confusion”.
It was very effective.
13. What is a promise?
The core idea behind promises is that it represents the result of an asynchronous
operation. A promise is in one of three different states:
- Pending: The initial state of a promise.
- Fulfilled: The state of a promise representing a successful operation.
- Rejected: The state of a promise representing a failed operation.
14. How does a promise work?
The State Diagram of a promise is as simple as this one:
15. Clarifying a little bit
- When pending, a promise:
○ may transition to either the fulfilled or rejected state.
- When fulfilled, a promise:
○ must not transition to any other state.
○ must have a value, which must not change.
- When rejected, a promise:
○ must not transition to any other state.
○ must have a reason, which must not change.
16. The “then” method
The “then” method is called when a promise is
either fulfilled or rejected.
This two conditions are treated by different
callbacks:
promise.then(onFulfilled, onRejected)
- onFulfilled(value): value of fulfilment of the
promise as its first argument
- onRejected(reason): reason of rejection of
the promise as its first argument. This
argument is optional.
functionReturningPromise.then(function(value){
// do something with value
}, function (reason) {
// do something if failed
})
17. Promise chaining
The “then” method always returns a new promise,
so it can be chained.
Even if your callbacks return a value, the promise
implementation will wrap it into a brand new
promise before returning it.
functionReturningPromise.then(function(value){
return 10
})
.then(function (number) {
console.log(number) // 10
})
.then(...)
.then(...)
.then(...)
.then(...)
.then(...)
// The chaining can go indefinetly
18. Error handling
If any error is thrown within a then callback, a
rejected promise will be automatically returned
with the error as its reason.
The immediately after then call will only execute
the onRejected callback.
If onRejected is not provided or is not a function,
the error will be passed to the next chained then.
If no then call in the chain have a onRejected
callback, the error will be thrown to the main code.
functionReturningPromise.then(function(value){
throw new Error(‘Something bad happened’)
})
.then(function (someArg) {
// do nothing
}, function (reason) {
console.log(reason) // Error: Something …
return 42 // Will return a resolved promise
})
19. Error bubbling
If onRejected is not provided or is not a function,
the error will be passed to the next chained then.
If the next chained then has the onRejected
callback, it will be called, giving you a possibility of
dealing with the error.
IMPORTANT: if you don’t throw a new error or
re-throw the error argument, the then method will
return a promise that is resolved with the return
value of the onRejected callback.
If no then call in the chain have a onRejected
callback, the error will be thrown to the main code.
functionReturningPromise.then(function(value){
throw new Error(‘Something bad happened’)
})
.then(function (number) {
console.log(number) // Will be bypassed
})
.then(function (someArg) {
// do nothing
}, function (reason) {
console.log(reason) // Error: Something …
// Will return a resolved promise
})
.then(function (number) {
console.log(number)
// undefined because the previous
// callback doesn’t return a value
})
20. Error catching
In most situations, you only want to deal with
possible errors once.
You can do this by adding a then call at the end of
your chain with only the onRejected callback.
This way, any subsequent then call after the error
throwing will be bypassed and the error will only
be handled by the last one.
Since the last then call is only for error catching,
you don’t need to set a onResolved callback and may
use null instead.
functionReturningPromise.then(function(value){
throw new Error(‘Something bad happened’)
})
.then(function (...) {
// Will be bypassed
})
.then(function (...) {
// Will be bypassed
})
.then(function (...) {
// Will be bypassed
})
.then(null, function (error) {
// Error: Something …
console.log(error)
})
22. Standardization
Promise A+¹ is a standard specification for promise
implementations.
It allows interoperability between different
promise libraries.
You don’t need to worry about what
implementation of promise a 3rd party module
uses, you can seamlessly integrate it into your code,
as long as it respects the A+ specs.
The specs are at the same time powerful and dead
simple: less than 100 lines of text in plain English.
¹ https://promisesaplus.com/
someLibrary.methodReturningPromise()
.then(function (result) {
return anotherLibrary.anotherPromise()
})
.then(function (anotherResult) {
// ...
})
23. I mean, a de facto standard...
Promises are now part of the core¹ of EcmaScript 6
(ES6).
That means it is available as part of the standard
library of modern Javascript engines:
● Node.js >= v0.12.*
● Any modern and updated browser (Firefox,
Chrome, Safari, Edge, etc. -- NOT IE)
¹ https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
² http://caniuse.com/#feat=promises
²
25. Parallel execution
Most of the promise implementations (including
the core one in ES6) have some extra methods will
allow you to have asynchronous code running in
parallel.
The Promise.all¹ method will take an array of
promises as an argument and will return a promise
that will only be resolved when and if all the input
promises are resolved.
The Promise.race¹ method will also take an array of
promises, but will return a promise that resolves to
the value of the first of the input to be resolved.
Promise.all([promise1, promise2, promise3])
.then(function (result) {
// result will be an array with the values
// of the input promises.
// The order is preserved, so you’ll have:
// [resPromise1, resPromise2, resPromise3]
})
Promise.race([promise1, promise2, promise3])
.then(function (result) {
// result will be the either resPromise1,
// resPromise2 or resPromise3, depending
// on which promise finishes firt
})
¹ Not part of the Promise A+ specification
26. The catch method
The catch¹ method is just a syntactic sugar around
the last-then-treats-error pattern discussed before.
functionReturningPromise.then(function(value){
throw new Error(‘Something bad happened’)
})
.then(null, function (error) {
console.log(error)
})
// Can be rewritten as following in most
// implementations of Promise:
functionReturningPromise.then(function(value){
throw new Error(‘Something bad happened’)
})
.catch(function (error) {
console.log(error)
})
¹ Not part of the Promise A+ specification
27. Creating settled promises
Another syntactic sugar allows you to create
promises that are already fulfilled or rejected,
through the helper methods Promise.resolve and
Promise.reject.
This can be very useful in cases that your interface
states you should return a promise, but you already
have the value to return (ex.: caching).
var cache = {}
functionReturningPromise.then(function(value){
throw new Error(‘Something bad happened’)
})
.then(function (result) {
if (cache[result] !== undefined) {
return Promise.resolve(cache[result])
} else {
return getFreshData(result)
.then(function (data) {
cache[result] = data
return data
)}
}
})
¹ This is not part of the Promise A+ specification
28. Non-standard¹ cool extras
The finally method allows you to have a callback
that will be executed either if the promise chain is
resolved or rejected.
The tap method is a really useful syntactic sugar
that allows you to intercept the result of a promise,
but automatically passing it down the chain.
The props method is like Promise.all, but resolves
to an object instead of an array.
db.connect() // Implemented using bluebird
.then(function() {
// run some queries
})
.finally(function () {
// no matter what, close the connection
db.disconnect()
})
var Promise = require('bluebird')
Promise.resolve(42)
// will print 42 into the console and return it
.tap(console.log.bind(console))
.then(function (result) {
// result is still 42
})
Promise.props({ a: getA(), b : getB()})
.then(function (obj) {
// Will print { a : …, b : … }
console.log(obj)
})
¹ Based on Bluebird (http://bluebirdjs.com/docs/) -- a full-featured promise implementation
30. Converting callback-based code
Bluebird¹ has some utility methods that will adapt
callback-based functions and libs to use promises.
The Promise.promisify method will take any
error-first callback and return a promise that will
be resolved if the callback is called without error or
rejected otherwise.
The Promise.promisifyAll method will take an
objects and iterate over all it’s methods and create
a new implementation of them, keeping the same
name, suffixed by “Async”.
Var Promise = require('bluebird’)
var fs = require('fs')
var readFileAsync = Promise.promisify(fs.readFile)
readFileAsync('someFile.ext')
.then(function (contents) {
// do something
})
// or...
Promise.promisifyAll(fs)
fs.readFileAsync('someFile.ext')
.then(function (contents) {
// do something
})
¹ http://bluebirdjs.com/