How To Use JavaScript Promises and Fetch API

As an interpreted language, JavaScript executes code line by line. However, it does not wait for the dependent code to execute before executing the next line.

To achieve this feature JavaScript introduces the callback function. Basically this is associated with the asynchronous operations in JavaScript.

But the issue with the callback function is if we have more than one asynchronous operation running at the same time. So it became hell to manage the code using the callback functions.

The problems are

  • Hard to understand the codes because the code becomes lengthier and nested structure.
  • Hard to manage the codes, because it is not clear which callbacks are called when and also there are so many callbacks to write to perform a particular task.
  • Also need not satisfy all the requirements

Here JavaScript introduces the concept of Promises.

JavaScript promises represent the eventual completion or failure of asynchronous operations. Promises are either resolved or rejected. Hence, when it resolves or rejects multiple asynchronous operations, it returns either success or an error.

Never miss an update from us. Join 10,000+ marketers and leaders.

Chaining Promises is provided to handle multiple asynchronous operations. So the code here is manageable and easy to understand. For your understanding, here are some examples of callbacks and promises.

Callbacks

[code language=”css”]
function validateMoney(money){

var interest = 100;

if(money){

return money+interest;

}else{

return money;

}

}

function getInterestMoney(money, callback) {

if (typeof money !== ‘number’) {

return callback(‘money is not a number’);

} else {

return callback(money)

}

}

const money = getInterestMoney(1200, validateMoney);

console.log(money);
[/code]

Promises:

[code language=”css”]
function getInterestMoney(money) {

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

if (typeof money !== ‘number’) {

reject(new Error(‘money is not a number’))

} else {

var interest = 100;

money = money+interest;

resolve(money);

}

})

}

getInterestMoney(1200)

.then((money) => {

console.log(money);

}).catch((error) => {

console.error(error);

});
[/code]

Fetch API:

Fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

Here is an example of the fetch api

[code language=”css”]
fetch(‘./api/some.json’)

.then(

function(response) {

if (response.status !== 200) {

console.log(‘Looks like there was a problem. Status Code: ‘ +

response.status);

return;

}

// Examine the text in the response

response.json().then(function(data) {

console.log(data);

});
[/code]

Chaining Promises

One of the great features of promises is the ability to chain them together. For fetch, this allows you to share logic across fetch requests.

Are you looking for a JavaScript developer

Contact Us

If you are working with a JSON API, you’ll need to check the status and parse the JSON for each response. You can simplify your code by defining the status and JSON parsing in separate functions which return promises, freeing you to only worry about handling the final data and the error case.

[code language=”css”]
function status(response) {

if (response.status >= 200 && response.status < 300) {

return Promise.resolve(response)

} else {

return Promise.reject(new Error(response.statusText))

}

}

function json(response) {

return response.json()

}

fetch(‘users.json’)

.then(status)

.then(json)

.then(function(data) {

console.log(‘Request succeeded with JSON response’, data);

}).catch(function(error) {

console.log(‘Request failed’, error);

});
[/code]

Hope the aforementioned guidelines will assist you in effectively utilizing JavaScript Promises and the Fetch API. For further insights and detailed information, recommend referring to the resources available on Google Developers.

If you require expert assistance with JavaScript development, you may consider engaging the services of Andolasoft’s experienced JavaScript developers

Let’s discuss.

Ruby On Rails Releases Fixes For DoS, XSS Vulnerabilities

In 18th March, Ruby on Rails released four new versions along with fixes for a number of vulnerabilities, which could have lead to denial of service attacks and XSS injections. According to a post in company’s blog a total of 4 vulnerabilities were addressed in version 3.2.13, 3.1.12 and 2.3.18 of Rails. The company wrote “All versions are impacted by one or more of these security issues,”

The patches were released for symbol denial service (DoS) vulnerability (CVE-2013-1854) in ActiveRecord function and for two cross-sites scripting vulnerabilities i.e. sanitize helper (CVE-2013-1857) and sanitize_css method in Action Pack (CVE-2013-1855).

According to one of the warnings, an additional XML parsing vulnerability in JDOM backend of ActiveSupport could have also allowed attackers to perform denial of service attack when using JRuby (CVE-2013-1856) or could have enabled to gain access to files stored in the app server.

The XSS vulnerability could have allowed attackers to embed tag URL, which executes arbitrary JavaScript code.

The XSS vulnerabilities in particular could have allowed an attacker to embed a tag containing a URL that executes arbitrary JavaScript code.

Ruby on rails developer have fixed a number of similar issues in Ruby on Rails last month, which also included a YAML issue in ActiveRecord that lead to remote code execution

Components And Platforms For Mobile Application Development

In the era of latest technologies the mobile applications are becoming more n more popular being handy and easy to use with the help of latest gadgets.

People are not only taking full advantage of these gadgets but also getting profit in the market through selling a variety of mobile applications. These are safe, user-friendly and easily accessible regardless of geographical location.

Prior to this technology the platforms like Symbian, Windows Mobile and Linux were used for mobile application development and the runtime environment like Mozilla Firefox, Opera Mini, RIM, virtual machines such as Java/J2ME, BREW, Flash were used to execute the applications. Now Android and Java are playing a vital role in a creative mobile application development environments.

Android is a framework built specifically for mobile devices. It has a well-designed operating system through Linux by Google and Open Handset Alliance.

Day-by-day it becomes the hottest, fast growing mobile platform in the world for mobile application development. Android is the exceptional platform that allows android developer to build unique, creative, sophisticate and multi tasking applications. In android smart phones the android applications can run simultaneously without affecting the performance.

Java is not only built for web pages or web application development but also it has huge contribution towards mobile application development. Using Java, html and css a java developer can build more powerful & faster mobile applications than the old generation applications written in C. Most smart phone mobile applications are built with J2ME components. J2ME mobile applications are more popular and widely used platform for wireless phones among the top manufacturing smart phone companies like BlackBerry, iOS, Android.

Andolasoft is backed by a team having strong analytical skill & solid expertise in mobile application development in various platforms like Android and Java to satisfy your needs. You will get the right help & support from Andolasoft development team for any kind of mobile application development.