Promises, promises: A quick introduction to JavaScript concurrency

A quick introduction to JavaScript concurrency At some point in your life as a programmer, you’ll need to deal with code that runs asynchronously. Normally, code runs one command after the other. Nice and predictably, It goes from top to…
The post Promises, promises: A quick introduction to JavaScript concurrency appeared first on Treehouse Blog.

Link: http://blog.teamtreehouse.com/javascript-concurrency

Promises That Don’t Fail

Introduction
My co-worker, Jason Kaiser, created a way for Promises not to fail, called sureThing. It has 3 benefits to your code that we’ll illustrate below, including prior art in other programming languages so you know this isn’t some made-up concept.
What Is a SureThing?
A sureThing is a function that wraps a Promise to ensure it never fails. The return value given to the .then is an object, letting you know if the operation succeeded or not.

Link: https://dzone.com/articles/promises-that-dont-fail?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Flow Control in Modern JS: Callbacks to Promises to Async/Await

JavaScript is regularly claimed to be asynchronous. What does that mean? How does it affect development? How has the approach changed in recent years?
Consider the following code:
result1 = doSomething1();
result2 = doSomething2(result1);

Most languages process each line synchronously. The first line runs and returns a result. The second line runs once the first has finished regardless of how long it takes.
Single-thread Processing
JavaScript runs on a single processing thread. When executing in a browser tab, everything else stops. This is necessary because changes to the page DOM can’t occur on parallel threads; it would be dangerous to have one thread redirecting to a different URL while another attempts to append child nodes.
This is rarely evident to the user, because processing occurs quickly in small chunks. For example, JavaScript detects a button click, runs a calculation, and updates the DOM. Once complete, the browser is free to process the next item on the queue.
(Side note: other languages such as PHP also use a single thread but may be managed by by a multi-threaded server such as Apache. Two requests to the same PHP page at the same time can initiate two threads running isolated instances of the PHP runtime.)
Going Asynchronous with Callbacks
Single threads raise a problem. What happens when JavaScript calls a “slow” process such as an Ajax request in the browser or a database operation on the server? That operation could take several seconds — even minutes. A browser would become locked while it waited for a response. On the server, a Node.js application would not be able to process further user requests.
The solution is asynchronous processing. Rather than wait for completion, a process is told to call another function when the result is ready. This is known as a callback, and it’s passed as an argument to any asynchronous function. For example:
doSomethingAsync(callback1);
console.log(‘finished’);

// call when doSomethingAsync completes
function callback1(error) {
if (!error) console.log(‘doSomethingAsync complete’);
}

doSomethingAsync() accepts a callback function as a parameter (only a reference to that function is passed so there’s little overhead). It doesn’t matter how long doSomethingAsync() takes; all we know is that callback1() will be executed at some point in the future. The console will show:
finished
doSomethingAsync complete

Callback Hell
Often, a callback is only ever called by one asynchronous function. It’s therefore possible to use concise, anonymous inline functions:
doSomethingAsync(error => {
if (!error) console.log(‘doSomethingAsync complete’);
});

A series of two or more asynchronous calls can be completed in series by nesting callback functions. For example:
async1((err, res) => {
if (!err) async2(res, (err, res) => {
if (!err) async3(res, (err, res) => {
console.log(‘async1, async2, async3 complete.’);
});
});
});

Unfortunately, this introduces callback hell — a notorious concept that even has its own web page! The code is difficult to read, and will become worse when error-handling logic is added.
Callback hell is relatively rare in client-side coding. It can go two or three levels deep if you’re making an Ajax call, updating the DOM and waiting for an animation to complete, but it normally remains manageable.
The situation is different on OS or server processes. A Node.js API call could receive file uploads, update multiple database tables, write to logs, and make further API calls before a response can be sent.
Promises
ES2015 (ES6) introduced Promises. Callbacks are still used below the surface, but Promises provide a clearer syntax that chains asynchronous commands so they run in series (more about that in the next section).
To enable Promise-based execution, asynchronous callback-based functions must be changed so they immediately return a Promise object. That object promises to run one of two functions (passed as arguments) at some point in the future:

resolve: a callback function run when processing successfully completes, and
reject: an optional callback function run when a failure occurs.

In the example below, a database API provides a connect() method which accepts a callback function. The outer asyncDBconnect() function immediately returns a new Promise and runs either resolve() or reject() once a connection is established or fails:
const db = require(‘database’);

// connect to database
function asyncDBconnect(param) {

return new Promise((resolve, reject) => {

db.connect(param, (err, connection) => {
if (err) reject(err);
else resolve(connection);
});

});

}

Node.js 8.0+ provides a util.promisify() utility to convert a callback-based function into a Promise-based alternative. There are a couple of conditions:

the callback must be passed as the last parameter to an asynchronous function, and
the callback function must expect an error followed by a value parameter.

Example:
// Node.js: promisify fs.readFile
const
util = require(‘util’),
fs = require(‘fs’),
readFileAsync = util.promisify(fs.readFile);

readFileAsync(‘file.txt’);

Various client-side libraries also provide promisify options, but you can create one yourself in a few lines:
// promisify a callback function passed as the last parameter
// the callback function must accept (err, data) parameters
function promisify(fn) {
return function() {
return new Promise(
(resolve, reject) => fn(
…Array.from(arguments),
(err, data) => err ? reject(err) : resolve(data)
)
);
}
}

// example
function wait(time, callback) {
setTimeout(() => { callback(null, ‘done’); }, time);
}

const asyncWait = promisify(wait);

ayscWait(1000);

The post Flow Control in Modern JS: Callbacks to Promises to Async/Await appeared first on SitePoint.

Link: https://www.sitepoint.com/flow-control-callbacks-promises-async-await/

The Dark Side of Promises

Since the release of es6 many new features have found their way into NodeJS, but non had quite the same impact as promises. Promises have been developed for the browser before es6 was even a thing. There were several implementations that have been used like jQuery’s deferred object before the standard made them obsolete. Promises […]
The post The Dark Side of Promises appeared first on David Walsh Blog.

Link: https://davidwalsh.name/dark-side-promises

Angular Observables and Promises – How to Use Them

Angular, as we all know, is a JavaScript framework that makes it easy to build web applications. RxJS is really about bringing the principles of functional programming to JavaScript.
Functional Programming in JavaScript?
It all started with the rise of asynchronicity or asynchronous JavaScript, where we have data that is flowing through our application coming from different sources, for example, APIs, Web sockets and User-triggered events and timers. We have a situation where we can’t control when any of this data is sent through our application. Neither can we decide the order in which it happens, so having a more functional paradigm would help resolve that. You want your application to be more predictable, but the scaling up of applications that run client side means less predictability.

Link: https://dzone.com/articles/angular-observables-and-promises-how-to-use-them

Six Tiny But Awesome ES7 + ES8 Features

Development of new features for the core JavaScript language has really improved over the last five years, thanks in part to JavaScript frameworks pushing the limits and proving how important given functionality can be.  My previous ES6 posts, Six Tiny But Awesome ES6 Features and Six More Tiny But Awesome ES6 Features, highlighted a dozen […]
The post Six Tiny But Awesome ES7 + ES8 Features appeared first on David Walsh Blog.

Link: https://davidwalsh.name/es7-es8-features

JavaScript fetch with Timeout

The fetch API started out as a target for criticism because of lack of timeout and request cancelation.  While those criticisms could be argued as fair or not, the you can’t deny that the fetch API has been pretty awesome.  As we’ve always done, if a feature is missing, we can always shim it in. […]
The post JavaScript fetch with Timeout appeared first on David Walsh Blog.

Link: https://davidwalsh.name/fetch-timeout

Async Operations in React Redux Applications

This post was originally posted at Codebrahma.
JavaScript is a single-threaded programming language. That is, when you have code something like this …

… the second line doesn’t get executed till the first one gets completed. Mostly this won’t be a problem, since millions of calculations are performed by the client or server in a second. We notice the effects only when we’re performing a costly calculation (a task that takes noticeable time to complete — a network request which takes some time to return back).
Why did I show only an API call (network request) here? What about other async operations? An API call is a very simple and useful example for describing how to deal with an asynchronous operation. There are other operations, like setTimeout(), performance-heavy calculations, image loading, and any event-driven operations.
While structuring our application, we need to consider how asynchronous execution impacts structuring. For example, consider fetch() as a function that performs an API call (network request) from the browser. (Forget if it is an AJAX request. Just think of the behavior as either asynchronous or synchronous in nature.) The time elapsed while the request is processed on the server doesn’t happen on the main thread. So your JS code will keep getting executed, and once the request returns a response it will update the thread.
Consider this code:
userId = fetch(userEndPoint); // Fetch userId from the userEndpoint
userDetails = fetch(userEndpoint, userId) // Fetch for this particular userId.

In this case, since fetch() is asynchronous, we won’t be having userId when we try to fetch userDetails. So we need to structure it in a way that ensures the second line executes only when the first returns a response.
Most modern implementations of network requests are asynchronous. But this doesn’t always help, since we depend on the previous API response data for the subsequent API calls. Let’s look at how particularly we can structure this in ReactJS/Redux applications.
React is a front-end library used for making user interfaces. Redux is a state container that can manage the whole state of the application. With React in combination with Redux, we can make efficient applications that scale well. There are several ways to structure async operations in such a React application. For each method, let’s discuss the pros and cons in relation to these factors:

code clarity
scalability
ease of error handling.

For each method, we’ll perform these two API calls:
1. Fetching city from userDetails (First API response)
Let’s assume the endpoint is /details. It will have the city in the response. The response will be an object:
userDetails : {

city: ‘city’,

};

2. Based on the user city we will fetch all restaurants in the city
Let’s say the endpoint is /restuarants/:city. The response will be an array:
[‘restaurant1’, ‘restaurant2’, …]

Remember that we can do the second request only when we finish doing the first (since it’s dependent on the first request). Let’s look at various ways to do this:

directly using promise or async await with setState
using Redux Thunk
using Redux-Saga
using Redux Observables.

Particularly I have chosen the above methods because they’re the most popularly used for a large-scale project. There are still other methods that can be more specific to particular tasks and that don’t have all the features required for a complex app (redux-async, redux-promise, redux-async-queue to name a few).
Promises

A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved (e.g., a network error occurred). — Eric Elliot

In our case, we’ll use the axios library to fetch data, which returns a promise when we make a network request. That promise may resolve and return the response or throw an error. So, once the React Component mounts, we can straight away fetch like this:
componentDidMount() {
axios.get(‘/details’) // Get user details
.then(response => {
const userCity = response.city;
axios.get(`/restaurants/${userCity}`)
.then(restaurantResponse => {
this.setState({
listOfRestaurants: restaurantResponse, // Sets the state
})
})
})
}

This way, when the state changes (due to fetching), Component will automatically re-render and load the list of restaurants.
Async/await is a new implementation with which we can make async operations. For example, the same thing can be achieved by this:
async componentDidMount() {
const restaurantResponse = await axios.get(‘/details’) // Get user details
.then(response => {
const userCity = response.city;
axios.get(`/restaurants/${userCity}`)
.then(restaurantResponse => restaurantResponse
});

this.setState({
restaurantResponse,
});
}

Both of these are the simplest of all methods. Since the entire logic is inside the component, we can easily fetch all the data once the component loads.
Drawbacks in the method
The problem will be when doing complex interactions based on the data. For example, consider the following cases:

We don’t want the thread in which JS is being executed to be blocked for network request.
All the above cases will make the code very complex and difficult to maintain and test.
Also, scalability will be a big issue, since if we plan to change the flow of the app, we need to remove all the fetches from the component.
Imagine doing the same if the component is at the top of the parent child tree. Then we need to change all the data dependent presentational components.
Also to note, the entire business logic is inside the component.

How we can improve from here?
1. State Management
In these cases, using a global store will actually solve half of our problems. We’ll be using Redux as our global store.
2. Moving business logic to correct place
If we think of moving our business logic outside of the component, then where exactly can we do that? In actions? In reducers? Via middleware? The architecture of Redux is such that it’s synchronous in nature. The moment you dispatch an action (JS objects) and it reaches the store, the reducer acts upon it.
3. Ensuring there’s a separate thread where async code is executed and any change to global state can be retrieved through subscription

From this, we can get an idea that if we’re moving all the fetching logic before reducer — that is either action or middleware — then it’s possible to dispatch the correct action at the correct time.
For example, once the fetch starts, we can dispatch({ type: ‘FETCH_STARTED’ }), and when it completes, we can dispatch({ type: ‘FETCH_SUCCESS’ }).
Want to develop a React JS application?
[affiliate-section title=”Recommended Courses"][affiliate-card title="The Best Way to Learn React for Beginners" affiliatename="Wes Bos" text="A step-by-step training course to get you building real world React.js + Firebase apps and website components in a couple of afternoons. Use coupon code ‘SITEPOINT’ at checkout to get 25% off." url="https://ReactForBeginners.com/friend/SITEPOINT" imageurl="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/07/1501203893wesbos.jpg"][/affiliate-section]
Using Redux Thunk
Redux Thunk is middleware for Redux. It basically allows us to return function instead of objects as an action. This helps by providing dispatch and getState as arguments for the function. We use the dispatch effectively by dispatching the necessary actions at the right time. The benefits are:

allowing multiple dispatches inside the function
relating of business logic to the fetch will be outside of React components and moved to actions.

In our case, we can rewrite the action like this:
export const getRestaurants = () => {
return (dispatch) => {
dispatch(fetchStarted()); // fetchStarted() returns an action

fetch(‘/details’)
.then((response) => {
dispatch(fetchUserDetailsSuccess()); // fetchUserDetailsSuccess returns an action
return response;
})
.then(details => details.city)
.then(city => fetch(‘/restaurants/city’))
.then((response) => {
dispatch(fetchRestaurantsSuccess(response)) // fetchRestaurantsSuccess(response) returns an action with the data
})
.catch(() => dispatch(fetchError())); // fetchError() returns an action with error object
};
}

As you can see, we now have a good control of when to dispatch what type of action. Each function call like fetchStarted(), fetchUserDetailsSuccess(), fetchRestaurantsSuccess() and fetchError() dispatches a plain JavaScript object of a type and additional details if required. So now it’s the job of the reducers to handle each action and update the view. I haven’t discussed the reducer, since it’s straightforward from here and the implementation might be varying.
For this to work, we need to connect the React component with Redux and bind the action with the component using the Redux library. Once this is done, we can simply call this.props.getRestaurants(), which in turn will handle all the above tasks and update the view based on the reducer.
In terms of its scalability, Redux Thunk can be used in apps which don’t involve complex controls over async actions. Also, it works seamlessly with other libraries, as discussed in the topics of the next section.
But still, it’s a little difficult to do certain tasks using Redux Thunk. For example, we need to pause the fetch in between, or when there are multiple such calls, and allow only the latest, or if some other API fetches this data and we need to cancel.
We can still implement those, but it will be little complicated to do exactly. Code clarity for complex tasks will be little poor when compared with other libraries, and maintaining it will be difficult.
Continue reading %Async Operations in React Redux Applications%

Link: https://www.sitepoint.com/async-operations-react-redux-applications/

Node.js Port Scanner

Node.js has become an incredible tool for creating services or utilities that act like a service.  Usually it’s npm start, wait a moment, and you’ll see the utility provide an address and port; a good example being localhost:8000.  One thing that bugs me about this pattern is if you have many service-based utilities that you […]
The post Node.js Port Scanner appeared first on David Walsh Blog.

Link: https://davidwalsh.name/javascript-port-scanner

async & await

JavaScript promises were a revelation in JavaScript, providing an alternative to the JavaScript callback hell we’d quickly found ourselves in.  Promises also allowed us to introduce and better handle asynchronous tasks.  While promises were an improvement over callback hell, they still require lots of thens which can become messy.  I’ve really taken to ES2017’s async and […]
The post async & await appeared first on David Walsh Blog.

Link: https://davidwalsh.name/async-await