Promises provide a consistent way to write asynchronous code in JavaScript by abstracting callbacks into objects. Some key benefits of promises include: handling errors through rejection instead of nested callbacks, ability to chain operations together through promise methods like .then(), and restoring synchronous-like control flow. The document discusses how promises improve on traditional callback-based patterns and provides examples of converting common asynchronous patterns to use promises.
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
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()
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.
This document summarizes different types of tests for Spring Boot applications, including unit tests, integration tests, and sliced tests. It discusses tools for mocking dependencies like MockRestServiceServer, Testcontainers for integration with Docker, and annotations like @MockBean and @SpyBean. Context caching, properties, and dirty context handling are also covered. The document concludes with an upcoming talk on JUnit 5.
The document provides an introduction to asynchronous JavaScript. It discusses callbacks and their disadvantages like callback hell. Promises are introduced as a better way to handle asynchronous code by making it easier to write and chain asynchronous operations. Async/await is described as syntactic sugar that allows asynchronous code to be written more readably in a synchronous style using await and try/catch. Key aspects like the event loop, microtask queue, and Promise methods like all and race are explained. Overall the document aims to help understand what makes asynchronous code different and newer methods like promises and async/await that improve handling asynchronous operations in JavaScript.
This document provides an overview of asynchronous JavaScript. It discusses how JavaScript uses a single thread and event queue. It introduces asynchronous functions and loading scripts asynchronously. It covers the requestIdleCallback function for background tasks. The document also provides an in-depth overview of promises in JavaScript for asynchronous code, including the promise lifecycle, then and catch methods, and creating promises using the Promise constructor.
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
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()
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.
This document summarizes different types of tests for Spring Boot applications, including unit tests, integration tests, and sliced tests. It discusses tools for mocking dependencies like MockRestServiceServer, Testcontainers for integration with Docker, and annotations like @MockBean and @SpyBean. Context caching, properties, and dirty context handling are also covered. The document concludes with an upcoming talk on JUnit 5.
The document provides an introduction to asynchronous JavaScript. It discusses callbacks and their disadvantages like callback hell. Promises are introduced as a better way to handle asynchronous code by making it easier to write and chain asynchronous operations. Async/await is described as syntactic sugar that allows asynchronous code to be written more readably in a synchronous style using await and try/catch. Key aspects like the event loop, microtask queue, and Promise methods like all and race are explained. Overall the document aims to help understand what makes asynchronous code different and newer methods like promises and async/await that improve handling asynchronous operations in JavaScript.
This document provides an overview of asynchronous JavaScript. It discusses how JavaScript uses a single thread and event queue. It introduces asynchronous functions and loading scripts asynchronously. It covers the requestIdleCallback function for background tasks. The document also provides an in-depth overview of promises in JavaScript for asynchronous code, including the promise lifecycle, then and catch methods, and creating promises using the Promise constructor.
Whitebox testing of Spring Boot applicationsYura Nosenko
This document discusses whitebox testing of Spring Boot applications. It begins with introductions and backgrounds, then discusses issues with existing testing frameworks like TestNG and JUnit 4. It proposes alternatives like Spock and JUnit 5, highlighting advantages of each. It also provides an overview of Spring Boot testing capabilities, focusing on integration testing support, transaction handling, main components, and reactive support. It concludes with examples of setting up Spring Boot testing with Spock and JUnit 5.
ReactJS is arguably the most popular Javascript framework around for web development today. With more and more teams exploring and adopting React, here is TechTalks presentation elaborating fundamentals of React, in a code along session
This document provides an overview of ASP.NET Web API, a framework for building HTTP-based services. It discusses key Web API concepts like REST, routing, actions, validation, OData, content negotiation, and the HttpClient. Web API allows building rich HTTP-based apps that can reach more clients by embracing HTTP standards and using HTTP as an application protocol. It focuses on HTTP rather than transport flexibility like WCF.
This talk introduces Spring's REST stack - Spring MVC, Spring HATEOAS, Spring Data REST, Spring Security OAuth and Spring Social - while refining an API to move higher up the Richardson maturity model
This document discusses challenges with asynchronous JavaScript programming using callbacks and promises, and introduces several approaches to help address these challenges, including async/await, generators, reactive programming with Rx observables, and functional reactive programming with Cycle.js. It provides examples of callback hell and promise limitations. Functional reactive programming uses functional utilities like map and filter to automatically propagate changes through observable data streams. Cycle.js implements a functional reactive paradigm for building asynchronous apps in a simple, extensible, and testable way by containing side effects and making data flows explicit.
The document discusses Redux Toolkit, a framework for building Redux applications. It introduces key Redux concepts like actions, reducers, and middleware. It explains how Redux Toolkit simplifies Redux setup with utilities like thunk and Immer.js. It demonstrates Redux Toolkit APIs like configureStore, createAction, createReducer, and createSlice that generate action creators and reducer logic to update state in response to actions.
- React is a JavaScript library for building user interfaces that uses a virtual DOM for faster re-rendering on state changes.
- Everything in React is a component that can have states, props, and lifecycle methods like render(). Components return JSX elements.
- Props are used for passing data to components in a unidirectional flow, while states allow components to re-render on changes.
- The render() method returns the view, accessing props and state values. Forms and events also follow React conventions.
Spring Boot is a framework that makes it easy to create stand-alone, production-grade Spring based Applications that can be "just run". It takes an opinionated view of the Spring platform and third-party libraries so that new and existing Spring developers can quickly get started with minimal configuration. Key features include automatic configuration of Spring, embedded HTTP servers, starters for common dependencies, and monitoring endpoints.
Maven is a build tool that can manage a project's build process, dependencies, documentation and reporting. It uses a Project Object Model (POM) file to store build configuration and metadata. Maven has advantages over Ant like built-in functionality for common tasks, cross-project reuse, and support for conditional logic. It works by defining the project with a POM file then running goals bound to default phases like compile, test, package to build the project.
The document outlines a React workshop covering what React is, its core concepts, and coding with React. It begins with an introduction and overview of React. It then covers key React concepts like components, the virtual DOM, JSX, state and props. Finally, it demonstrates how to start coding with React by rendering a component, using state, and working with forms. Resources for further learning are also provided at the end.
React Js Basic Details and Descriptions
Frontend Javascript Library, to make decent SPA
The fastest way to build a segregated component based front end for software development.
Spring Data provides a unified model for data access and management across different data access technologies such as relational, non-relational and cloud data stores. It includes utilities such as repository support, object mapping and templating to simplify data access layers. Spring Data MongoDB provides specific support for MongoDB including configuration, mapping, querying and integration with Spring MVC. It simplifies MongoDB access through MongoTemplate and provides a repository abstraction layer.
Spring Boot is a framework for creating stand-alone, production-grade Spring based Applications that can be "just run". It provides starters for auto-configuration of common Spring and third-party libraries providing features like Thymeleaf, Spring Data JPA, Spring Security, and testing. It aims to remove boilerplate configuration and promote "convention over configuration" for quick development. The document then covers how to run a basic Spring Boot application, use Rest Controllers, Spring Data JPA, Spring Security, and testing. It also discusses deploying the application on a web server and customizing through properties files.
This document provides an overview of Flask, a microframework for Python. It discusses that Flask is easy to code and configure, extensible via extensions, and uses Jinja2 templating and SQLAlchemy ORM. It then provides a step-by-step guide to setting up a Flask application, including creating a virtualenv, basic routing, models, forms, templates, and views. Configuration and running the application are also covered at a high level.
Optional was introduced in Java 8 to help deal with null references in a safer way. Optional wraps an object that may or may not be present, and supports methods like map, filter, and flatMap to operate on the wrapped value in a functional style. Using Optional helps avoid NullPointerExceptions and makes it clear whether a value is present or absent, improving code readability and safety over directly using null references.
This document discusses JavaScript promises as an abstraction pattern for handling asynchronous code. It explains why promises are useful by describing some of the issues with callback-based asynchronous code, such as callback hell and lack of readability. The document then provides examples of how to create and use promises to handle sequential and parallel asynchronous tasks in a more maintainable way using chaining and batching. It also discusses how promises are supported in browsers, Node.js, and common promise libraries like Q, RSVP, when.js, and Bluebird.
(Presented at JSConf US 2013. Be sure to check out the speaker notes!)
Frustration, a rant, a test suite, a gist. Then, community awesomeness. Boom! Promises/A+ was born.
Promise are an old idea for abstracting asynchronous code, but have only recently made their way into JavaScript. We'll look at the power they provide via two striking examples that go beyond the usual "escape from callback hell" snippets. First we'll show how, with ES6 generators, they can act as shallow coroutines to give us back code just as simple as its synchronous counterpart. Then we'll look at how they can be used as proxies for remote objects, across <iframe>, worker, or web socket boundaries.
However, the most interesting aspect of Promises/A+ is not just the code it enables, but how we worked to create it. We didn't join a standards body, but instead formed a GitHub organization. We had no mailing list, only an issue tracker. We submitted pull requests, made revisions, debated versions tags, etc.—all in the open, on GitHub. And, we succeeded! Promises/A+ is widely used and implemented today, with its extensible core forming the starting point of any discussions about promises. Indeed, this community-produced open standard has recently been informing the incorporation of promises into ECMAScript and the DOM. I'd like to share the story of how this happened, the lessons we learned along the way, and speculate on the role such ad-hoc, community-driven, and completely open specifications have for the future of the web.
Whitebox testing of Spring Boot applicationsYura Nosenko
This document discusses whitebox testing of Spring Boot applications. It begins with introductions and backgrounds, then discusses issues with existing testing frameworks like TestNG and JUnit 4. It proposes alternatives like Spock and JUnit 5, highlighting advantages of each. It also provides an overview of Spring Boot testing capabilities, focusing on integration testing support, transaction handling, main components, and reactive support. It concludes with examples of setting up Spring Boot testing with Spock and JUnit 5.
ReactJS is arguably the most popular Javascript framework around for web development today. With more and more teams exploring and adopting React, here is TechTalks presentation elaborating fundamentals of React, in a code along session
This document provides an overview of ASP.NET Web API, a framework for building HTTP-based services. It discusses key Web API concepts like REST, routing, actions, validation, OData, content negotiation, and the HttpClient. Web API allows building rich HTTP-based apps that can reach more clients by embracing HTTP standards and using HTTP as an application protocol. It focuses on HTTP rather than transport flexibility like WCF.
This talk introduces Spring's REST stack - Spring MVC, Spring HATEOAS, Spring Data REST, Spring Security OAuth and Spring Social - while refining an API to move higher up the Richardson maturity model
This document discusses challenges with asynchronous JavaScript programming using callbacks and promises, and introduces several approaches to help address these challenges, including async/await, generators, reactive programming with Rx observables, and functional reactive programming with Cycle.js. It provides examples of callback hell and promise limitations. Functional reactive programming uses functional utilities like map and filter to automatically propagate changes through observable data streams. Cycle.js implements a functional reactive paradigm for building asynchronous apps in a simple, extensible, and testable way by containing side effects and making data flows explicit.
The document discusses Redux Toolkit, a framework for building Redux applications. It introduces key Redux concepts like actions, reducers, and middleware. It explains how Redux Toolkit simplifies Redux setup with utilities like thunk and Immer.js. It demonstrates Redux Toolkit APIs like configureStore, createAction, createReducer, and createSlice that generate action creators and reducer logic to update state in response to actions.
- React is a JavaScript library for building user interfaces that uses a virtual DOM for faster re-rendering on state changes.
- Everything in React is a component that can have states, props, and lifecycle methods like render(). Components return JSX elements.
- Props are used for passing data to components in a unidirectional flow, while states allow components to re-render on changes.
- The render() method returns the view, accessing props and state values. Forms and events also follow React conventions.
Spring Boot is a framework that makes it easy to create stand-alone, production-grade Spring based Applications that can be "just run". It takes an opinionated view of the Spring platform and third-party libraries so that new and existing Spring developers can quickly get started with minimal configuration. Key features include automatic configuration of Spring, embedded HTTP servers, starters for common dependencies, and monitoring endpoints.
Maven is a build tool that can manage a project's build process, dependencies, documentation and reporting. It uses a Project Object Model (POM) file to store build configuration and metadata. Maven has advantages over Ant like built-in functionality for common tasks, cross-project reuse, and support for conditional logic. It works by defining the project with a POM file then running goals bound to default phases like compile, test, package to build the project.
The document outlines a React workshop covering what React is, its core concepts, and coding with React. It begins with an introduction and overview of React. It then covers key React concepts like components, the virtual DOM, JSX, state and props. Finally, it demonstrates how to start coding with React by rendering a component, using state, and working with forms. Resources for further learning are also provided at the end.
React Js Basic Details and Descriptions
Frontend Javascript Library, to make decent SPA
The fastest way to build a segregated component based front end for software development.
Spring Data provides a unified model for data access and management across different data access technologies such as relational, non-relational and cloud data stores. It includes utilities such as repository support, object mapping and templating to simplify data access layers. Spring Data MongoDB provides specific support for MongoDB including configuration, mapping, querying and integration with Spring MVC. It simplifies MongoDB access through MongoTemplate and provides a repository abstraction layer.
Spring Boot is a framework for creating stand-alone, production-grade Spring based Applications that can be "just run". It provides starters for auto-configuration of common Spring and third-party libraries providing features like Thymeleaf, Spring Data JPA, Spring Security, and testing. It aims to remove boilerplate configuration and promote "convention over configuration" for quick development. The document then covers how to run a basic Spring Boot application, use Rest Controllers, Spring Data JPA, Spring Security, and testing. It also discusses deploying the application on a web server and customizing through properties files.
This document provides an overview of Flask, a microframework for Python. It discusses that Flask is easy to code and configure, extensible via extensions, and uses Jinja2 templating and SQLAlchemy ORM. It then provides a step-by-step guide to setting up a Flask application, including creating a virtualenv, basic routing, models, forms, templates, and views. Configuration and running the application are also covered at a high level.
Optional was introduced in Java 8 to help deal with null references in a safer way. Optional wraps an object that may or may not be present, and supports methods like map, filter, and flatMap to operate on the wrapped value in a functional style. Using Optional helps avoid NullPointerExceptions and makes it clear whether a value is present or absent, improving code readability and safety over directly using null references.
This document discusses JavaScript promises as an abstraction pattern for handling asynchronous code. It explains why promises are useful by describing some of the issues with callback-based asynchronous code, such as callback hell and lack of readability. The document then provides examples of how to create and use promises to handle sequential and parallel asynchronous tasks in a more maintainable way using chaining and batching. It also discusses how promises are supported in browsers, Node.js, and common promise libraries like Q, RSVP, when.js, and Bluebird.
(Presented at JSConf US 2013. Be sure to check out the speaker notes!)
Frustration, a rant, a test suite, a gist. Then, community awesomeness. Boom! Promises/A+ was born.
Promise are an old idea for abstracting asynchronous code, but have only recently made their way into JavaScript. We'll look at the power they provide via two striking examples that go beyond the usual "escape from callback hell" snippets. First we'll show how, with ES6 generators, they can act as shallow coroutines to give us back code just as simple as its synchronous counterpart. Then we'll look at how they can be used as proxies for remote objects, across <iframe>, worker, or web socket boundaries.
However, the most interesting aspect of Promises/A+ is not just the code it enables, but how we worked to create it. We didn't join a standards body, but instead formed a GitHub organization. We had no mailing list, only an issue tracker. We submitted pull requests, made revisions, debated versions tags, etc.—all in the open, on GitHub. And, we succeeded! Promises/A+ is widely used and implemented today, with its extensible core forming the starting point of any discussions about promises. Indeed, this community-produced open standard has recently been informing the incorporation of promises into ECMAScript and the DOM. I'd like to share the story of how this happened, the lessons we learned along the way, and speculate on the role such ad-hoc, community-driven, and completely open specifications have for the future of the web.
This document discusses callbacks, promises, and generators for handling asynchronous code in JavaScript. It begins by explaining callbacks and the issues they can cause like "callback hell". It then introduces promises as an alternative using libraries like Q that allow chaining asynchronous operations together. Generators are also covered as a way to write asynchronous code that looks synchronous when combined with promises through libraries like CO. Overall, it recommends using an asynchronous pattern supported by a library to manage complex asynchronous code.
Although Web and mobile apps are getting more capable every day, often your application makes the most sense on the desktop. In this talk, we’ll look at some recent technologies that have allowed significant desktop apps — like Barnes & Noble’s NOOK Study e-textbook reader, or Adobe’s Brackets IDE — to be written in HTML5 and JavaScript. Projects like the Chromium Embedded Framework, node-webkit, and AppJS provide an excellent native-to-JS bridge. With them in hand, you can bring the full power of the Node.js and front-end ecosystems to bear, while still gaining the advantages of running as a native app.
This document discusses new features coming to JavaScript in ECMAScript 6, including:
1) Block scope keywords "let" and "const" that allow for block-level scoping of variables.
2) Shorthand syntax for object literals and method definitions.
3) Destructuring assignments for extracting values from objects and arrays.
4) Default parameter values, rest parameters, and spread syntax for working with functions and arrays.
5) New features like modules, classes, and imports for better organizing code.
- JavaScript has come a long way from its early days of form validation and image rollovers in 1995 to modern innovations like ES2015, Promises, async/await, and Web Assembly.
- Today, JavaScript features like classes, arrow functions, and template strings in ES2015 are widely adopted, and new standards like Promises, generators, and async programming have revolutionized asynchronous JavaScript.
- Emerging web platform technologies like Web Components, Service Workers, and CSS Paint enable new kinds of custom elements, offline/progressive web apps, and painting APIs, while proposals like decorators, value types, and module loading continue pushing the language forward.
How to Win Friends and Influence Standards BodiesDomenic Denicola
# How to Make Friends and Influence Standards Bodies
The greatest strength of the web is its openness. But not everyone appreciates how we arrived at the open web of today. A recent trend has cast standards bodies as bureaucracies that never accomplish anything of substance, while the heroic community innovates and implements “from scratch.”
Reality is much less black-and-white: sandboxes like Node.js have received much from the web platform and language that spawned them, and have a lot to contribute back. Standards bodies are composed of implementers and community members willing to engage, not ivory tower philosophers handing down bad, never-tested APIs from on high. And real gains could be made for both sides—with some effort.
This talk is part stories, and part lessons; it’s meant both to teach, and to open the floodgates for collaboration. You’ll hear about ways in which community input has had great impact on the standards process for the better, as in the case of web audio or adding promises to ES6. But you’ll also be taught communication and coalition-building skills that, from what I see, are sorely needed by many community members. How can you get involved and shape the future of the web and JavaScript platforms in a direction that will help everyone? Who are the key players and processes that they follow?
Finally, together we’ll brainstorm on and identify some key areas where your expertise and hard-learned lessons could help the web platform toward future solutions for problems it’s encountered.
The document discusses JavaScript promises and how they can be used to handle asynchronous operations. Promises allow asynchronous functions to return values asynchronously by attaching callbacks to the promise object. This avoids callback hell and makes asynchronous code easier to read and maintain. The document covers how promises can be chained together, executed in parallel, cached, and passed around between functions. It also discusses promise implementations in different frameworks like jQuery, Angular, and how promises can interact across frameworks.
Keeping promises has advantages like gaining trust, making friends, and following the prophet, while breaking promises leads to losing friends and trust. The document discusses what a promise is and its importance through a poem, compares the advantages of keeping promises to the disadvantages of breaking them, and lists two promises Allah made in the Quran about rewarding righteousness and keeping promises. It concludes with thanks for watching.
Let’s talk about what Microsoft has given us for building ambitious, real-world Windows 8 apps in HTML5 and JavaScript—but also what’s missing, and how we can fill in the gaps.
ES6 is Nigh is a presentation on the future of JavaScript. It discusses the history of JavaScript and why ES6 is important for advancing the language. The presentation outlines many new features being added in ES6, such as arrow functions, classes, modules, template strings, symbols, generators, and proxies. It emphasizes that ES6 is purely additive and introduces these features without breaking backwards compatibility.
This document discusses best practices for creating RESTful APIs. It covers three main topics: representing resources with URLs and HTTP verbs, using the HTTP protocol machinery like status codes and caching, and linking resources together through hypermedia. URLs should represent resources, verbs should represent actions, and standard HTTP features like status codes and conditional requests should be used. Well-designed REST APIs represent application state through linked resources and relationships rather than embedding actions in URLs.
This document discusses the use of present tense verbs to express future meaning. It provides examples of sentences using present tense verbs like "will", "going to" to indicate future actions such as taking a sweater to the cinema, taking a taxi if the weather is bad, brushing teeth after breakfast, and going to the park after watching a movie.
In 2010, a photo-sharing startup launched—on a single, closed platform. Over the next two years, it gained over 100 million active users, before being acquired by Facebook for one. billion. dollars.
Only half a year after *that* did they finally release a web app.
Instagram's main purpose was sharing photos and commenting on them. If this isn't a perfect fit for the open web platform, I don't know what is. And yet the app was planted neatly within Apple's walled garden, without even an API to speak of. How did things go so wrong?
The web needs to catch up, and fast. If we want to preserve all the virtues of the web—shareable URLs, indexable content, open standards, instantly deployed updates, and so on—then we need to make the web platform more attractive, both to developers and users. We need to explore the final frontier of web development: *true* web apps, of the kind that will delight our users (and our investors). But we're not quite there … yet.
In this talk, I want to explore the efforts underway to bring the web platform up to speed as a genuine competitor. We have the most momentum of any platform in history, but there are still many unanswered questions. What are the major functionality gaps, and how are we closing them? Can we make app development as easy for web as it is for native? How do we fix mobile performance? Can you even use a web app while you're offline? I want to tell you about that not-too-distant future where these problems have been solved. Editors are speccing up new APIs; implementers are leveling up their browsers; and the community is building new frameworks. Together, we're slowly but surely pushing into that final frontier. And once we're past it, the mobile web will be a natural choice for the next big content-sharing app, enabling us to share by simply sending a URL—from any browser, to any device, on any platform.
This document discusses client-side JavaScript packages and module systems. It begins by describing CommonJS and AMD module systems, noting problems with AMD including configuration complexity and inability to easily consume third-party code. It then introduces the concept of packages as a better unit of code reuse than modules alone. NPM is presented as a package manager that solves problems of downloading, installing dependencies, and accessing other packages' code. Key aspects of NPM packages like directory structure and package.json are outlined. The document concludes by briefly covering NPM features like dependency hierarchies, Git dependencies, and using NPM without publishing to the public registry.
The document discusses the importance of contracts in both Islamic law and common law. In Islam, a contract (aqd) requires offer and acceptance, as well as the consent of both parties. The terms must be for a halal object and allowed under Islamic revelation. Written contracts are emphasized in the Quran and by the Prophet Muhammad. Fulfilling obligations and avoiding deception are stressed. In common law, contracts create legally binding relationships if they meet requirements like offer, acceptance, and consideration. Written contracts are preferred as they clearly outline parties' expectations and responsibilities.
Domains were added to Node.js in 0.8, but their use and workings have been a relative mystery. In short, domains are a structured way of reacting to uncaught exceptions; for example, when creating an HTTP server, you can use domains to send 500 errors when exceptions occur instead of crashing your server. This talk will go over what domains are, how to use them, and some of the subtleties behind how they work.
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!
The discovery of unit testing and test-driven development was one of the most important parts of my growth as a developer. The ability to write simple, small pieces of code that could verify the behavior of my application was in itself quite useful. And the ability to refactor without fear, just by running the test suite, changed how I program. But the real benefits come in how unit tests shape your application code: more testable code is often more well thought-out, more decoupled, and more extensible.
In this talk, I'll give a whirlwind introduction to unit testing as a concept and as a practice. I want you fully convinced it's the best thing to happen to software development, if you aren't already. Once we're on the same page there, I'll take a deep dive into what makes a good unit test. This involves testing tools such as spies, stubs, and mocks, concepts like code coverage, and practices like dependency injection that shape your application code. The most important lesson will be on how to focus on singular, isolated units of code in your testing, as this guides you toward building modular, flexible, and comprehensible applications.
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.
The document discusses different patterns for handling asynchronous code in JavaScript: callbacks, promises, and AMD (Asynchronous Module Definition). It outlines issues with nested callbacks and inflexible APIs. Promises and AMD aim to address these by allowing composition of asynchronous operations and defining module dependencies. The document provides examples of implementing PubSub with events, making and piping promises, and using AMD to load dependencies asynchronously. It concludes that callbacks should generally be avoided in favor of promises or AMD for asynchronous code.
The document discusses Javascript Promises and the Q library for handling asynchronous code. It explains what Promises are, how they avoid callback pyramids or "Pyramids of Doom", and how the Q library can be used to generate and control Promises. The Q library allows wrapping asynchronous functions in Promises and provides methods for chaining Promises together and handling errors across asynchronous operations.
- JavaScript patterns like custom events, deferreds, and pub/sub can help manage asynchronous processes in the browser environment. Custom events allow defining and triggering custom events. Deferreds help manage callbacks and caching of asynchronous results. Pub/sub implements a publisher/subscriber pattern for loose coupling between modules. These patterns help modularize applications and decouple components.
An opinionated intro to Node.js - devrupt hospitality hackathonLuciano Mammino
A talk presenting an opinionated introduction to Node.js, proving a simple introduction to the async model, some common async patterns and some other interesting Node.js tricks.
This document provides an overview of promises and deferred objects. It discusses the history of promises, including early use in 1976 and implementations in Dojo, Node.js, Q.js and Futures.js. The document defines a promise as an object representing a value that is not yet known, and a deferred as representing work that is not yet finished. It outlines the CommonJS Promises/A specification and details the states a promise can be in. The document then examines jQuery's implementation of promises and deferreds and provides examples of how to use deferreds and promises to manage asynchronous code.
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
A promise represents a deferred execution of an asynchronous operation. Promises allow functions to write asynchronous code that looks synchronous by using the .then() method to specify callbacks. The .then() method can return data immediately, return a new promise, or return a rejection. Errors can be handled using .catch(), and multiple concurrent promises can be combined with $q.all(). Finally, promises provide a consistent way to handle both success and failure cases for asynchronous code.
The next version of JavaScript, ES6, is starting to arrive. Many of its features are simple enhancements to the language we already have: things like arrow functions, class syntax, and destructuring. But other features will change the way we program JavaScript, fundamentally expanding the capabilities of the language and reshaping our future codebases. In this talk we'll focus on two of these, discovering the the myriad possibilities of generators and the many tricks you can pull of with template strings.
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 2015.
http://www.ivanomalavolta.com
Realm Mobile Database - An IntroductionKnoldus Inc.
Realm is a cross-platform mobile database.It is a data persistence solution designed specifically for mobile applications. Realm store data in a universal, table-based format
It is simple as data are directly exposed as objects and queryable by code, removing the need for ORM's maintenance issues. Realm is faster than raw SQLite on common operations, while maintaining an extremely rich feature set.
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.
We will cover whole of the web development basics comprising of HTML, CSS, JavaScript in this series.
Following are topics useful for any newbie to intermediate who is interested in learning Web Development
Symfony2: What's all the buzz about?
Follow along as we download, install and get a hands-on experience using Symfony2. This presentation shows you how to get started with Symfony and introduces you to the large group of new PHP libraries coming from the Symfony2 community. You'll see examples of how to create pages, use template inheritance, and create a simple JSON API.
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 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.
Slowly but surely, promises have spread throughout the JavaScript ecosystem, standardized by ES 2015 and embraced by the web platform. But the world of asynchronous programming contains more patterns than the simple single-valued async function call that promises represent. What about things like streams, observables, async iterators—or even just cancelable promises? How do they fit, both in the conceptual landscape and in your day-to-day programming?
For the last year, I've been working to bring an implementation of I/O streams to the browser. Meanwhile, designs for a cancelable promise type (sometimes called "tasks") are starting to form, driven by the needs of web platform APIs. And TC39 has several proposals floating around for more general asynchronous iteration. We'll learn about these efforts and more, as I guide you through the frontiers of popular libraries, language design, and web standards.
Two years ago I inherited jsdom, a project of breathtaking scope. In essence, it aims to simulate a browser in JavaScript, by implementing JavaScript versions of a wide variety of web standards (much more than just the DOM). While maintaining jsdom for the last two years, and eventually bringing it to a 1.0 release, I learned an incredible amount about the web. I want to share with you what I’ve learned: the history of the standards and implementations of them that make up the web; the interaction between seemingly-disparate parts of the platform; and all about the strange APIs we’ve come to know and love. You should walk away from this talk with a new appreciation for how browsers work—and how, through the ongoing effort of a community of contributors and package maintainers, we’ve been able to recreate one in pure JavaScript.
The document discusses using ES6 features in real-world applications. It provides examples of using arrow functions, classes, destructuring, template literals, and default parameters to write cleaner code. It also discusses tools for enabling ES6 features that are not yet fully supported, such as transpilers, and flags in Node.js and Chrome to enable more experimental features. Overall, the document advocates adopting ES6 features that make code more concise and readable.
Streams are a fundamental programming primitive for representing the flow of data through your system. It's time we brought this powerful tool to the web. What if we could stream data from a HTTP request, through a web worker that transforms it, and then into a <video> tag? Over the last year, I've been working on the WHATWG streams specification, which builds upon the lessons learned in Node.js, to provide a suitable abstraction for needs of the extensible web.
I'll discuss briefly why streams are important, what they enable, and the role we envision them playing in the future of the web platform. Mostly, though, I want to help you understand streams, at a deep level. In the course of writing this specification, I've learned a lot about streams, and I want to share that knowledge with you. At the core, they are a very simple and beautiful abstraction. I think we've done a good job capturing that abstraction, and producing an API the web can be proud of. I'd love to tell you all about it.
Our favorite language is now powering everything from event-driven servers to robots to Git clients to 3D games. The JavaScript package ecosystem has quickly outpaced past that of most other languages, allowing our vibrant community to showcase their talent. The front-end framework war has been taken to the next level, with heavy-hitters like Ember and Angular ushering in the new generation of long-lived, component-based web apps. The extensible web movement, spearheaded by the newly-reformed W3C Technical Architecture Group, has promised to place JavaScript squarely at the foundation of the web platform. Now, the language improvements of ES6 are slowly but surely making their way into the mainstream— witness the recent interest in using generators for async programming. And all the while, whispers of ES7 features are starting to circulate…
JavaScript has grown up. Now it's time to see how far it can go.
In June 2013, we published the Extensible Web Manifesto, declaring that the web platform should be built a series of extensible layers. Low-level capabilities, like hardware access, cryptography, or the parser, should be exposed to web developers through JavaScript, and higher-level features, like HTML tags or animations, should be explained in terms of those primitives. This allows JavaScript developers to extend the web platform without rewriting it from scratch in JavaScript, customizing it for the needs of their applications and creating a virtuous cycle wherein web developers prototype higher-level features that implementers can later pull in.
In this talk, I want to explore the concrete meaning of the extensible web. What initiatives already under way can we see through this lens? What ideas are still gestating, and need your input as a web developer? How will this new philosophy end up impacting you? I want to show you the future of the web platform, where developers like you are involved from the beginning in designing and prototyping APIs, and have enough low-level tools at your fingertips to solve any problem you face. And I want to bring it all back to our favorite language, JavaScript, which is the glue that makes this all work together.
In text format at http://domenic.me/2013/10/07/the-extensible-web/
Node.js is an exciting new platform for building web applications in JavaScript. With its unique I/O model, it excels at the sort of scalable and real-time situations we are increasingly demanding of our servers. And the ability to use JavaScript for both the client and server opens up many possibilities for code sharing, expertise reuse, and rapid development.
This class is intended for those with some basic knowledge of JavaScript, interested in an introduction to the Node.js ecosystem and development platform. We'll discuss how to get started with Node, and why you would want to. We'll then explore Node's module and package system, demonstrating several of the more popular and impressive packages that exemplify the type of tasks Node excels at. These include low-level HTTP streaming with the http module, high-level bidirectional websocket communication with socket.io, and server-browser code sharing with browserify, jsdom, and node-canvas.
Discover top-tier mobile app development services, offering innovative solutions for iOS and Android. Enhance your business with custom, user-friendly mobile applications.
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving
Manufacturing custom quality metal nameplates and badges involves several standard operations. Processes include sheet prep, lithography, screening, coating, punch press and inspection. All decoration is completed in the flat sheet with adhesive and tooling operations following. The possibilities for creating unique durable nameplates are endless. How will you create your brand identity? We can help!
Conversational agents, or chatbots, are increasingly used to access all sorts of services using natural language. While open-domain chatbots - like ChatGPT - can converse on any topic, task-oriented chatbots - the focus of this paper - are designed for specific tasks, like booking a flight, obtaining customer support, or setting an appointment. Like any other software, task-oriented chatbots need to be properly tested, usually by defining and executing test scenarios (i.e., sequences of user-chatbot interactions). However, there is currently a lack of methods to quantify the completeness and strength of such test scenarios, which can lead to low-quality tests, and hence to buggy chatbots.
To fill this gap, we propose adapting mutation testing (MuT) for task-oriented chatbots. To this end, we introduce a set of mutation operators that emulate faults in chatbot designs, an architecture that enables MuT on chatbots built using heterogeneous technologies, and a practical realisation as an Eclipse plugin. Moreover, we evaluate the applicability, effectiveness and efficiency of our approach on open-source chatbots, with promising results.
What is an RPA CoE? Session 1 – CoE VisionDianaGray10
In the first session, we will review the organization's vision and how this has an impact on the COE Structure.
Topics covered:
• The role of a steering committee
• How do the organization’s priorities determine CoE Structure?
Speaker:
Chris Bolin, Senior Intelligent Automation Architect Anika Systems
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/how-axelera-ai-uses-digital-compute-in-memory-to-deliver-fast-and-energy-efficient-computer-vision-a-presentation-from-axelera-ai/
Bram Verhoef, Head of Machine Learning at Axelera AI, presents the “How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-efficient Computer Vision” tutorial at the May 2024 Embedded Vision Summit.
As artificial intelligence inference transitions from cloud environments to edge locations, computer vision applications achieve heightened responsiveness, reliability and privacy. This migration, however, introduces the challenge of operating within the stringent confines of resource constraints typical at the edge, including small form factors, low energy budgets and diminished memory and computational capacities. Axelera AI addresses these challenges through an innovative approach of performing digital computations within memory itself. This technique facilitates the realization of high-performance, energy-efficient and cost-effective computer vision capabilities at the thin and thick edge, extending the frontier of what is achievable with current technologies.
In this presentation, Verhoef unveils his company’s pioneering chip technology and demonstrates its capacity to deliver exceptional frames-per-second performance across a range of standard computer vision networks typical of applications in security, surveillance and the industrial sector. This shows that advanced computer vision can be accessible and efficient, even at the very edge of our technological ecosystem.
AppSec PNW: Android and iOS Application Security with MobSFAjin Abraham
Mobile Security Framework - MobSF is a free and open source automated mobile application security testing environment designed to help security engineers, researchers, developers, and penetration testers to identify security vulnerabilities, malicious behaviours and privacy concerns in mobile applications using static and dynamic analysis. It supports all the popular mobile application binaries and source code formats built for Android and iOS devices. In addition to automated security assessment, it also offers an interactive testing environment to build and execute scenario based test/fuzz cases against the application.
This talk covers:
Using MobSF for static analysis of mobile applications.
Interactive dynamic security assessment of Android and iOS applications.
Solving Mobile app CTF challenges.
Reverse engineering and runtime analysis of Mobile malware.
How to shift left and integrate MobSF/mobsfscan SAST and DAST in your build pipeline.
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.
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...Jason Yip
The typical problem in product engineering is not bad strategy, so much as “no strategy”. This leads to confusion, lack of motivation, and incoherent action. The next time you look for a strategy and find an empty space, instead of waiting for it to be filled, I will show you how to fill it in yourself. If you’re wrong, it forces a correction. If you’re right, it helps create focus. I’ll share how I’ve approached this in the past, both what works and lessons for what didn’t work so well.
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor IvaniukFwdays
At this talk we will discuss DDoS protection tools and best practices, discuss network architectures and what AWS has to offer. Also, we will look into one of the largest DDoS attacks on Ukrainian infrastructure that happened in February 2022. We'll see, what techniques helped to keep the web resources available for Ukrainians and how AWS improved DDoS protection for all customers based on Ukraine experience
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.
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
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
The Microsoft 365 Migration Tutorial For Beginner.pptxoperationspcvita
This presentation will help you understand the power of Microsoft 365. However, we have mentioned every productivity app included in Office 365. Additionally, we have suggested the migration situation related to Office 365 and how we can help you.
You can also read: https://www.systoolsgroup.com/updates/office-365-tenant-to-tenant-migration-step-by-step-complete-guide/
4. Callbacks are a hack
• They are literally the simplest thing that could work.
• But as a replacement for synchronous control flow, they suck.
• There’s no consistency in callback APIs.
• There’s no guarantees.
• We lose the flow of our code writing callbacks that tie
together other callbacks.
• We lose the stack-unwinding semantics of exceptions, forcing
us to handle errors explicitly at every step.
@DOMENIC
5. Promises are the right abstraction
Instead of calling a passed callback, return a promise:
readFile("file.txt", function (err, result) {
// continue here…
});
// becomes
var promiseForResult = readFile("file.txt");
@DOMENIC
6. Promise guarantees
promiseForResult.then(onFulfilled, onRejected);
• Only one of onFulfilled or onRejected will be called.
• onFulfilled will be called with a single fulfillment value (⇔ return value).
• onRejected will be called with a single rejection reason (⇔ thrown exception).
• If the promise is already settled, the handlers will still be called once you
attach them.
• The handlers will always be called asynchronously.
@DOMENIC
7. Promises can be chained
var transformedPromise = originalPromise.then(onFulfilled, onRejected);
• If the called handler returns a value, transformedPromise will be resolved
with that value:
▫ If the returned value is a promise, we adopt its state.
▫ Otherwise, transformedPromise is fulfilled with that value.
• If the called handler throws an exception, transformedPromise will be
rejected with that exception.
@DOMENIC
8. The Sync ⇔ Async Parallel
var result, threw = false;
try {
result = doSomethingSync(); doSomethingAsync().then(
} catch (ex) { process,
threw = true; handle
handle(ex); );
}
if (!threw) process(result);
@DOMENIC
9. Case 1: Simple Functional Transform
var user = getUser();
var userName = user.name;
// becomes
var userNamePromise = getUser().then(function (user) {
return user.name;
});
@DOMENIC
10. Case 2: Reacting with an Exception
var user = getUser();
if (user === null)
throw new Error("null user!");
becomes
var userPromise = getUser().then(function (user) {
if (user === null)
throw new Error("null user!");
return user;
});
@DOMENIC
11. Case 3: Handling an Exception
try {
updateUser(data);
} catch (ex) {
console.log("There was an error:", ex);
}
// becomes
var updatePromise = updateUser(data).then(undefined, function (ex) {
console.log("There was an error:", ex);
});
@DOMENIC
12. Case 4: Rethrowing an Exception
try {
updateUser(data);
} catch (ex) {
throw new Error("Updating user failed. Details: " + ex.message);
}
// becomes
var updatePromise = updateUser(data).then(undefined, function (ex) {
throw new Error("Updating user failed. Details: " + ex.message);
});
@DOMENIC
13. Bonus Async Case: Waiting
var name = promptForNewUserName();
updateUser({ name: name });
refreshUI();
// becomes
promptForNewUserName()
.then(function (name) {
return updateUser({ name: name });
})
.then(refreshUI);
@DOMENIC
14. Promises Give You Back Exception Propagation
getUser("Domenic", function (user) {
getBestFriend(user, function (friend) {
ui.showBestFriend(friend);
});
});
@DOMENIC
15. Promises Give You Back Exception Propagation
getUser("Domenic", function (err, user) {
if (err) {
ui.error(err);
} else {
getBestFriend(user, function (err, friend) {
if (err) {
ui.error(err);
} else {
ui.showBestFriend(friend);
}
});
}
});
@DOMENIC
16. Promises Give You Back Exception Propagation
getUser("Domenic")
.then(getBestFriend)
.then(ui.showBestFriend, ui.error);
@DOMENIC
17. Promises as First-Class Objects
• Because promises are first-class objects, you can build simple operations on
them instead of tying callbacks together:
// Fulfills with an array of results, or rejects if any reject
all([getUserData(), getCompanyData()]);
// Fulfills as soon as either completes, or rejects if both reject
any([storeDataOnServer1(), storeDataOnServer2()]);
// If writeFile accepts promises as arguments, and readFile returns one:
writeFile("dest.txt", readFile("source.txt"));
@DOMENIC
19. Prehistory
• “Discovered” circa 1989.
• Much of modern promises are inspired by the E programming language.
• They’ve made their way into many languages:
▫ .NET’s Task<T>
▫ java.util.concurrent.Future
▫ Python’s PEP 3148
▫ C++ 11’s std::future
@DOMENIC
20. CommonJS Promises/A
• Inspired by early implementations: ref_send, Dojo, …
• But…
▫ Underspecified
▫ Missing key features
▫ Often misinterpreted
@DOMENIC
21. $.Deferred
jQuery’s $.Deferred is a very buggy attempted implementation, that
entirely misses the sync ⇔ async parallel:
• Multiple fulfillment values and rejection reasons
• Only supports scenario 1 (functional transformation); doesn’t handle
errors
• Not interoperable with other “thenables.”
• Before 1.8, did not support returning a promise
@DOMENIC
28. I Think It’s Been a Success
• >20 conformant implementations, with more showing up constantly
▫ Even one in ActionScript 3!
• The creation of RSVP.js specifically so that Ember could have
Promises/A+ compatible promises
• Version 1.1 of the spec almost ready, nailing down some unspecified
points
• Several other sibling specs under active development: promise creation,
cancellation, progress, …
@DOMENIC
29. Even the DOM and TC39 are getting in on this
• Alex Russell’s DOMFuture promise library, for possibly using promises in
future or existing DOM APIs
• Convergence with Mark Miller’s concurrency strawman, for integrating
promises into the language
@DOMENIC
31. First, Choose a Library
• My top picks:
▫ Q, by Kris Kowal and myself: https://github.com/kriskowal/q
▫ When.js, by Brian Cavalier: https://github.com/cujojs/when
▫ RSVP.js, by Yehuda Katz: https://github.com/tildeio/rsvp.js
• If you ever see a jQuery promise, kill it with fire:
var realPromise = Q(jQueryPromise);
var realPromise = when(jQueryPromise);
@DOMENIC
32. Keep The Sync ⇔ Async Parallel In Mind
• Use promises for single operations that can result in fulfillment
(⇔ returning a value) or rejection (⇔ throwing an exception).
• If you’re ever stuck, ask “how would I structure this code if it
were synchronous?”
▫ The only exception is multiple parallel operations, which has no
sync counterpart.
@DOMENIC
33. Promises Are Not
• A replacement for events
• A replacement for streams
• A way of doing functional reactive programming
They work together:
• An event can trigger from one part of your UI, causing the event handler
to trigger a promise-returning function
• A HTTP request function can return a promise for a stream
@DOMENIC
34. The Unhandled Rejection Pitfall
This hits the top of the stack:
throw new Error("boo!");
This stays inert:
var promise = doSomething().then(function () {
throw new Error("boo!");
});
@DOMENIC
35. Avoiding the Unhandled Rejection Pitfall
• Always either:
▫ return the promise to your caller;
▫ or call .done() on it to signal that any unhandled rejections should explode
function getUserName() {
return getUser().then(function (user) {
return user.name;
});
}
getUserName().then(function (userName) {
console.log("User name: ", userName);
}).done(); @DOMENIC
42. Coroutines
“Coroutines are computer program
components that generalize subroutines to
allow multiple entry points for suspending
and resuming execution at certain
locations.”
@DOMENIC
43. Generators = Shallow Coroutines
function* fibonacci() {
var [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (n of fibonnaci()) {
console.log(n);
} @DOMENIC
44. http://taskjs.org/
task.js: Generators + Promises = Tasks
spawn(function* () {
var data = yield $.ajax(url);
$("#result").html(data);
var status = $("#status").html("Download complete.");
yield status.fadeIn().promise();
yield sleep(2000);
status.fadeOut();
});
@DOMENIC
45. task.js Even Works on Exceptions
spawn(function* () {
var user;
try {
user = yield getUser();
} catch (err) {
ui.showError(err);
return;
}
ui.updateUser(user);
});
@DOMENIC
46. Remote Promises
userPromise
.get("friends")
.get("0")
.invoke("calculateFriendshipCoefficient")
.then(displayInUI)
.done();
What if … userPromise referred to a remote object?!
@DOMENIC
47. https://github.com/kriskowal/q-connection/
Q Connection
• Can connect to web workers, <iframe>s, or web sockets
var Q = require("q");
var Connection = require("q-comm");
var remote = Connection(port, local);
// a promise for a remote object!
var userPromise = remote.getUser();
@DOMENIC
48. Promise Pipelining
• Usual “remote object” systems fall down in a few ways:
▫ They would see the first request, and return the entire friends array.
▫ They can’t invoke methods that involved closed-over state, only methods
that you can send over the wire.
▫ Workarounds involve complex serialization and rehydration approaches, i.e.
require coupling the client and the server.
• With promises as the abstraction, we can “pipeline” messages from one
side to the other, returning the ultimately-desired result.
@DOMENIC
49. • Start using promises in your code: client, server,
everywhere.
• Be aware that you want a Promises/A+ compatible
library—beware jQuery.
• Generators are almost ready in Firefox, Chrome, and
What’s next Node.js.
• Investigate promises for real-time communication with
Q-Connection.
• Look forward to promises in the DOM, and maybe some
syntactic support in ECMAScript 7!
@DOMENIC
Editor's Notes
Hook: how many used promises?jQuery promises or real promises?Want to talk about this in three parts: a ground-up view of the promise abstraction; a historical perspective on recent developments; and a practical guide to using them in your code.
What I really mean by this is “callback-accepting functions are a hack.”
First benefit: separating outputs from inputs.
- Consistency gains: never call back with more than one fulfillment value or rejection reason.
Just like a series of imperative statements.
And yet, we lived with it.
Spec development process through GitHub issue trackerPull requests, implementers weighing in, bugs opened by randoms, etc.Test suite!
Q has:Large, powerful API surfaceAdapters for Node.jsProgress supportSome support for long stack traces