Adam Daniels

Adam Daniels

1559117701

Getting Started with Promises in Nodejs

In this article, I will show how we can use Promises in Nodejs. Promises are kind of design patterns to remove the usage of unintuitive callbacks.

Promises are a built-in concurrency primitive that’s been part of JavaScript since ES6 in 2015. The Promise class has been included in Node.js since v4.0.0. That means, unless you’re on an unmaintained version of Node.js, you can use promises without any outside libraries.

Getting Started with Promises in Node.js

A promise is an object representation of a value that is being computed asynchronously. The easiest way to create a promise is using the Promise.resolve function.

// Create a promise with a pre-computed value 'Hello, World'
const promise = Promise.resolve('Hello, World!');

promise instanceof Promise; // true

The most important function for interacting with promises is the Promise#then function. To get the promise’s associated value once it is done being computed, you should call then():

// Prints "Hello, World"
promise.then(res => console.log(res));

There is no way to access a promise’s value directly. In other words, the only way to “unbox” promise into the value ‘Hello, World’ is by calling .then().

The Technical Details of Promises

You can think of a promise as an object representation of an asynchronous operation. Technically, a promise is a state machine representing the status of an asynchronous operation. A promise can be in one of 3 states:

  1. Pending. The operation is in progress.

  2. Fulfilled. The operation completed successfully.

  3. Rejected. The operation experienced an error.

Here’s a state diagram from Mastering Async/Await that demonstrates the possible states:

Getting Started with Promises in Nodejs

Once a promise is either fulfilled or rejected, it stays fulfilled or rejected. That is why a promise that is no longer pending is called settled.

Another important detail is that, as the client of a promise-based API, you can’t fulfill or reject a promise. Given a promise object, you cannot make the promise change state, even if it is pending. You can only react to what the promise does using functions like then().

Speaking of then(), let’s take another look at then() given the perspective of a promise as a state machine. The first parameter to then() is a function called onFulfilled.

promise.then(function onFulfilled(res) {
  console.log(res); // 'Hello, World'
});

As the name onFulfilled implies, Node.js will call your onFulfilled function if your promise changes state from pending to fulfilled. If you call then() on a function that is already fulfilled, Node.js will call onFulfilled immediately.

Errors and catch()

If promise changes state from pending to fulfilled, Node.js will call your onFulfilled function. What happens if promise changes state from pending to rejected?

Turns out the .then() function takes two function parameters, onFulfilled and onRejected. Node.js calls the onRejected function if your promise changes state from pending to rejected, or if the promise is already rejected.

promise.then(
  function onFulfilled(res) { console.log(res); },
  function onRejected(err) { console.log(err); }
);

If onRejected is null or undefined, Node.js will not treat that as an error. If a promise is rejected and it doesn’t have an onRejected handler, that will become an unhandled promise rejection.

Promises also have a Promise.reject function analagous to Promise.resolve(). Here’s an example of using Promise.reject() with an onRejected handler.

Promise.reject(new Error('Oops!')).then(null, function onRejected(err) {
  console.log(err.message); // Oops!
});

The .then(null, function onRejected() pattern is so common in promises that there’s a helper function for it: Promise#catch. The catch() function lets you add an onRejected handler without passing an onFulfilled() function.

Promise.reject(new Error('Oops!')).catch(function onRejected(err) {
  console.log(err.message); // Oops!
});

Chaining Promises

Promise chaining is what lets promises avoid deeply nested callbacks, also known as “callback hell”, “pyramid of doom”, and “banana code”.

Getting Started with Promises in Nodejs

The idea of promise chaining is that if you call then() with an onFulfilled() that function returns a new promise p, then() should return a promise that is “locked in” to match the state of p.

For example:

const p1 = Promise.resolve('p1');
// The `then()` function returns a promise!
const p2 = p1.then(() => Promise.resolve('p2'));

// Prints "p2"
p2.then(res => console.log(res));

In practice, promise chaining generally looks like a list of chained .then() calls. For example:

return asyncOperation1().
  then(res => asyncOperation2(res)).
  then(res => asyncOperation3(res)).
  // If any of `asyncOperation1()` - `asyncOperation3()` rejects, Node will
  // call this `onRejected()` handler.
  catch(function onRejected(err) { console.log(err); });

Now that you’ve seen the basics of promise chaining, lets see how you would use promise chaining with core Node.js APIs.

Using Promises with Core Node.js APIs

Node.js 10 introduced a promise-based API for the built-in fs module. That means you can read from and write to the file system using promises in Node.js.

To use the promise-based fs API, use the following syntax:

const fs = require('fs').promises; 

Now, suppose you want to read a file, replace all instances of ‘foo’ with ‘bar’, and write the file back to disk. Here’s how that might look with promise chaining.

const fs = require('fs').promises;

function replace(filename) {
  let handle;
  let contents;
  // Open a file handle
  return fs.open(filename, 'r+').
    then(_handle => {
      handle = _handle;
      // Read the contents of the file
      return handle.readFile();
    }).
    // Replace instances of 'foo' with 'bar' in the contents
    then(_contents => {
      contents = _contents.toString().replace(/foo/g, 'bar');
    }).
    // Empty out the file
    then(() => handle.truncate()).
    // Write the replaced contents to the file
    then(() => handle.writeFile(contents)).
    then(() => console.log('done')).
    // If any step fails, this `onRejected()` handler will get called.
    catch(err => console.log(err));
}

Converting Callbacks to Promises

Many older Node.js APIs are still written using callbacks. Node.js has a promisify function that can convert a function that uses Node.jscallback syntax to a function that returns a promise.

const util = require('util');

function usingCallback(callback) {
  // Call `callback()` after 50 ms
  setTimeout(() => callback(null, 'Hello, World'), 50);
}

const usingPromise = util.promisify(usingCallback);

// Prints "Hello, World" after 50ms.
usingPromise().then(res => console.log(res));

#node-js #javascript #web-development

What is GEEK

Buddha Community

Getting Started with Promises in Nodejs

Hire NodeJs Developer

Looking to build dynamic, extensively featured, and full-fledged web applications?

Hire NodeJs Developer to create a real-time, faster, and scalable application to accelerate your business. At HourlyDeveloper.io, we have a team of expert Node.JS developers, who have experience in working with Bootstrap, HTML5, & CSS, and also hold the knowledge of the most advanced frameworks and platforms.

Contact our experts: https://bit.ly/3hUdppS

#hire nodejs developer #nodejs developer #nodejs development company #nodejs development services #nodejs development #nodejs

How to Install NodeJS on Ubuntu 19.04

Overview
In this tutorial, you will learn how to install Node onto Ubuntu 19.04 Disco Dingo. We will cover installation from the default repositories and, for those wanting more recent releases, how to install from the NodeSource repositories.

Installing from Ubuntu
The Ubuntu 19.04 Disco Dingo repository includes NodeJS version 10.15. Like most packages found here, it certainly is not the most recent release; however, if stability is more important than features, it will be your preferred choice.

#nodejs #nodejs 10.x #nodejs 11.x #nodejs 12.x #nodejs 8.x

Top NodeJS Mobile App Development Company in USA

AppClues Infotech is one of the leading NodeJS app development company in USA that offering excellent NodeJS development services for web app development. We provide customized and high-quality NodeJS app development services to clients for different industries with advanced technology and functionalities.

Our dedicated app developers have years of experience in NodeJS development and thus successfully deliver cost-effective and highly customized solutions using the robust JavaScript engine of NodeJS.

Why Choose AppClues Infotech for NodeJS Application Development?
• Fast App Development
• Real-Time Application
• JSON (JavaScript Object Notation) in your Database
• Single Codebase
• Lower Cost
• Built-in NPM Support
• Inexpensive Testing and Hosting

For more info:
Website: https://www.appcluesinfotech.com/
Email: info@appcluesinfotech.com
Call: +1-978-309-9910

#top nodejs app development company in usa #nodejs web app development #nodejs development agency in usa #hire nodejs app developers in usa #custom nodejs app development company #best nodejs app development service company

Arvel  Miller

Arvel Miller

1603068240

Decoding Nodejs

The main goal of this blog is to explain the “Architecture of Nodejs” and to know how the Nodejs works behind the scenes,

Generally, most of the server-side languages, like PHP, ASP.NET, Ruby, and including Nodejs follows multi-threaded architecture. That means for each client-side request initiates a new thread or even a new process.

In Nodejs, all those requests from the clients are handled in a single-thread using shared resources concurrently as It follows the “Single-Threaded Event Loop Model”.

ARCHITECTURE OF NODEJS

What Is EVENT-LOOP?

Event-Loop programming is a flow control in an application-defined by events. The basic principle of Nodejs’s event-driven loop is implementing a central mechanism that hears for events and calls the callback function once an event is turning up.

Nodejs is an event-loop that implements a run-time environment model to achieve non-blocking asynchronous behavior runs on Google Chrome’s V8 engine.

#nodejs #nodejs-developer #nodejs-architecture #nodejs-tutorial #backend #javascript #beginners #event-loop

Carmen  Grimes

Carmen Grimes

1595494844

How to start an electric scooter facility/fleet in a university campus/IT park

Are you leading an organization that has a large campus, e.g., a large university? You are probably thinking of introducing an electric scooter/bicycle fleet on the campus, and why wouldn’t you?

Introducing micro-mobility in your campus with the help of such a fleet would help the people on the campus significantly. People would save money since they don’t need to use a car for a short distance. Your campus will see a drastic reduction in congestion, moreover, its carbon footprint will reduce.

Micro-mobility is relatively new though and you would need help. You would need to select an appropriate fleet of vehicles. The people on your campus would need to find electric scooters or electric bikes for commuting, and you need to provide a solution for this.

To be more specific, you need a short-term electric bike rental app. With such an app, you will be able to easily offer micro-mobility to the people on the campus. We at Devathon have built Autorent exactly for this.

What does Autorent do and how can it help you? How does it enable you to introduce micro-mobility on your campus? We explain these in this article, however, we will touch upon a few basics first.

Micro-mobility: What it is

micro-mobility

You are probably thinking about micro-mobility relatively recently, aren’t you? A few relevant insights about it could help you to better appreciate its importance.

Micro-mobility is a new trend in transportation, and it uses vehicles that are considerably smaller than cars. Electric scooters (e-scooters) and electric bikes (e-bikes) are the most popular forms of micro-mobility, however, there are also e-unicycles and e-skateboards.

You might have already seen e-scooters, which are kick scooters that come with a motor. Thanks to its motor, an e-scooter can achieve a speed of up to 20 km/h. On the other hand, e-bikes are popular in China and Japan, and they come with a motor, and you can reach a speed of 40 km/h.

You obviously can’t use these vehicles for very long commutes, however, what if you need to travel a short distance? Even if you have a reasonable public transport facility in the city, it might not cover the route you need to take. Take the example of a large university campus. Such a campus is often at a considerable distance from the central business district of the city where it’s located. While public transport facilities may serve the central business district, they wouldn’t serve this large campus. Currently, many people drive their cars even for short distances.

As you know, that brings its own set of challenges. Vehicular traffic adds significantly to pollution, moreover, finding a parking spot can be hard in crowded urban districts.

Well, you can reduce your carbon footprint if you use an electric car. However, electric cars are still new, and many countries are still building the necessary infrastructure for them. Your large campus might not have the necessary infrastructure for them either. Presently, electric cars don’t represent a viable option in most geographies.

As a result, you need to buy and maintain a car even if your commute is short. In addition to dealing with parking problems, you need to spend significantly on your car.

All of these factors have combined to make people sit up and think seriously about cars. Many people are now seriously considering whether a car is really the best option even if they have to commute only a short distance.

This is where micro-mobility enters the picture. When you commute a short distance regularly, e-scooters or e-bikes are viable options. You limit your carbon footprints and you cut costs!

Businesses have seen this shift in thinking, and e-scooter companies like Lime and Bird have entered this field in a big way. They let you rent e-scooters by the minute. On the other hand, start-ups like Jump and Lyft have entered the e-bike market.

Think of your campus now! The people there might need to travel short distances within the campus, and e-scooters can really help them.

How micro-mobility can benefit you

benefits-micromobility

What advantages can you get from micro-mobility? Let’s take a deeper look into this question.

Micro-mobility can offer several advantages to the people on your campus, e.g.:

  • Affordability: Shared e-scooters are cheaper than other mass transportation options. Remember that the people on your campus will use them on a shared basis, and they will pay for their short commutes only. Well, depending on your operating model, you might even let them use shared e-scooters or e-bikes for free!
  • Convenience: Users don’t need to worry about finding parking spots for shared e-scooters since these are small. They can easily travel from point A to point B on your campus with the help of these e-scooters.
  • Environmentally sustainable: Shared e-scooters reduce the carbon footprint, moreover, they decongest the roads. Statistics from the pilot programs in cities like Portland and Denver showimpressive gains around this key aspect.
  • Safety: This one’s obvious, isn’t it? When people on your campus use small e-scooters or e-bikes instead of cars, the problem of overspeeding will disappear. you will see fewer accidents.

#android app #autorent #ios app #mobile app development #app like bird #app like bounce #app like lime #autorent #bird scooter business model #bird scooter rental #bird scooter rental cost #bird scooter rental price #clone app like bird #clone app like bounce #clone app like lime #electric rental scooters #electric scooter company #electric scooter rental business #how do you start a moped #how to start a moped #how to start a scooter rental business #how to start an electric company #how to start electric scooterrental business #lime scooter business model #scooter franchise #scooter rental business #scooter rental business for sale #scooter rental business insurance #scooters franchise cost #white label app like bird #white label app like bounce #white label app like lime