This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

Getting Started With JavaScript Promises

 


Promises are one of the ways we can deal with asynchronous operations in JavaScript. Many people struggle with understanding how Promises work, so in this post I will try to explain them as simply as I can.

Promises are a broad topic so I can't go into every detail in this article. But you'll find an overall introduction to what Promises are, explanations of terms like resolve, reject, and chaining, and a code example for creating and using Promises.

Prerequisite : To understand this article better, check out my other post about JavaScript Callbacks.

What is a Promise ?


A promise in JavaScript is similar to a promise in real life. When we make a promise in real life, it is a guarantee that we are going to do something in the future. Because promises can only be made for the future.

A Promise has 2 Possible Outcomes : It will either be kept when the time comes, or it won’t.

This is also the same for promises in JavaScript. When we define a promise in JavaScript, it will be resolved when the time comes, or it will get rejected. 



Promises in JavaScript


First of all, a Promise is an Object. There are 3 States Of The Promise Object :

  • Pending: Initial State, before the Promise succeeds or fails
  • Resolved: Completed Promise
  • Rejected: Failed Promise
Representation Of the Process Of Promises

For example, when we request data from the server by using a Promise, it will be in pending mode until we receive our data.

If we achieve to get the information from the server, the Promise will be resolved successfully. But if we don’t get the information, then the Promise will be in the rejected state.

Additionally, if there are multiple requests, then after the first Promise is resolved (or rejected), a new process will start to which we can attach it directly by a method called chaining.

If you prefer, you can also watch the video version below:

What is the difference between Callbacks and Promises?


The main difference between Callback Functions and Promises is that we attach a callback to a Promise rather than passing it. So we still use callback functions with Promises, but in a different way (chaining).

This is one of the greatest advantages of using Promises, but why?

What is Chaining?


Callback functions have been used alone for asynchronous operations in JavaScript for many years. But in some cases, using Promises can be a better option.

If there are multiple async operations to be done and if we try to use good-old Callbacks for them, we’ll find ourselves quickly inside a situation called Callback hell:

firstRequest(function(response) {  
    secondRequest(response, function(nextResponse) {    
        thirdRequest(nextResponse, function(finalResponse) {     
            console.log('Final response: ' + finalResponse);    
        }, failureCallback);  
    }, failureCallback);
}, failureCallback);

However if we handle the same operation with Promises, since we can attach Callbacks rather than passing them, this time the same code above looks much cleaner and easier to read:

firstRequest()
  .then(function(response) {
    return secondRequest(response);
}).then(function(nextResponse) {  
    return thirdRequest(nextResponse);
}).then(function(finalResponse) {  
    console.log('Final response: ' + finalResponse);
}).catch(failureCallback);

The code just above shows how multiple callbacks can be chained one after another. Chaining is one of the best features of Promises. 

Creating and Using A Promise Step by Step

Firstly, we use a constructor to create a Promise object:

const myPromise = new Promise();

It takes two parameters, one for success (resolve) and one for fail (reject):

const myPromise = new Promise((resolve, reject) => {  
    // condition
});

Finally, there will be a condition. If the condition is met, the Promise will be resolved, otherwise it will be rejected:

const myPromise = new Promise((resolve, reject) => {  
    let condition;  
    
    if(condition is met) {    
        resolve('Promise is resolved successfully.');  
    } else {    
        reject('Promise is rejected');  
    }
});

So we have created our first Promise. Now let's use it.

then( ) for resolved Promises:

If you revisit the picture at the beginning of this post, you'll see that there are 2 cases: One for resolved promises and one for rejected. If the Promise gets resolved (success case), then something will happen next (depends on what we do with the successful Promise).

myPromise.then();

The then( ) method is called after the Promise is resolved. Then we can decide what to do with the resolved Promise.

For example, let’s log the message to the console that we got from the Promise:

myPromise.then((message) => {

console.log(message); });

catch( ) for rejected Promises:

However, the then( ) method is only for resolved Promises. What if the Promise fails? Then, we need to use the catch( ) method.

Likewise we attach the then( ) method. We can also directly attach the catch( ) method right after then( ):

myPromise.then((message) => { 
    console.log(message);
}).catch((message) => { 
    console.log(message);
});

So if the promise gets rejected, it will jump to the catch( ) method and this time we will see a different message on the console.

Wrap Up

So this is how we create a Promise in JavaScript and use it for resolved and rejected cases. Promises are a broader topic, and there are many more things to learn about them. So understanding how they work takes time.

This post is just an introduction to Promises, and I hope you found it helpful for getting an idea about what JavaScript Promises are and how to use them.

If you want to learn more about Web Development, feel free to visit my Youtube Channel for more.

Thank you for reading!

Creating A Local Server From A Public Address

 


I’ve been developing websites for the better part of 10 years and one of my biggest issues was always local development and syncing local sites to live tests. Using a local environment is great because it is fast, but it isn’t viewable from afar and transfering somewhere means Database Operation, renaming tables, values and so on.

In this article, I’ll show you an easy way to run a local server which you can access from your phone and other mobile devices natively, and also broadcast over the Internet, which means sharing your work with clinets , without leaving good ol’ localhost.

Using Vagrant To Create A Local Environment

A short while ago I wrote an article here on Harsiddhi Academy about using Vagrant so I’ll only go over the basics here. For more info, take a look at the article! 

To get started, you’ll need to grab and install VirtualBox and Vagrant. Both are free and used to create a virtual machine which will run your server.

Now, create a folder to store your websites in. Let's use a directory named “Websites” within our main user directory. That would be /Users/[username]/Websites on OS X and C:/Users/[username]/Websites on Windows. 

Create a new folder named wordpress. This is where I’ll create the virtual machine. The idea is that each folder within Websites houses a separate virtual machine. While you can put as many websites on one virtual machine as you’d like, I do like to group them out by platforms - Exm: WordPress, Laravel, Custom

For the purposes of this tutorial I’ll be creating a WordPress website.

Inside the WordPress folder we’ll need to create two files, Vagrantfile and install.sh. These will be used to set up our virtual machineJeffrey Way has created two great starter files; you can grab his Vagrantfile and install.sh files.

Next, using the terminal, navigate to the WordPress directory and type vagrant up. This will take a while, since the box needs to be downloaded and then installed. Grab a cup of coffee and check out this post on 60+ WordPress tips while you wait.

Once the process is complete you should be able to go to 192.168.33.21 and see a properly served page. You content folder should be the html folder within the WordPress directory. You can now start adding files, install WordPress, or anything else you’d like.

Don’t forget to read the full Vagrant guide for more info on creating virtual hosts, mapping domains like mytest.dev and so on.

Opening Local Sites On The Same Network Using Gulp

While building a site you should be thinking about responsiveness. Small screens can be emulated to some extent by narrowing the browser window, but it’s just not the same experience, especially if you throw retina screens in the mix.

Ideally you’ll want to open your local website on your mobile devices. This is not too difficult to do, provided your devices are on the same network.

To get this done we’ll be using Gulp and Browsersync. Gulp is a tool for the automation of development, Browsersync is a great tool that can not only create a local server but syncronize scrolling, clicks, forms and more across devices.

Installing Gulp

Installing Gulp is very easy. Head on over to the Getting Started page for the instructions. One pre-requisite is NPM (Node Package Manager). The easiest way to get this is to install Node itself. Head on down to the Node Website for instructions.

Once you’ve used the npm install --global gulp command to install gulp globally, you need to add it to your project. The way to do this is to run npm install --save-dev gulp in the root folder of your project, then add a gulpfile.js file there.

At the moment let’s add a single line of code inside that file which indicates that we will be using Gulp itself.

1
var gulp = require('gulp');

If you’re interested in all the cool things Gulp can do like concatenating scripts, compiling Sass and LESS, optimizing images and so on, read our Guide To Gulp. In this article we’ll be focusing on creating a server.

Using Browsersync

Browsersync has a Gulp extension which we can install in two steps. First, let’s use npm to download it, then we add it to our Gulpfile.

Issue the npm install browser-sync gulp --save-dev command in the project root in the terminal; this will download the extension. Then, open the Gulpfile and add the following line to it:

1
var browserSync = require('browser-sync').create();

This lets Gulp know that we’ll be using Browsersync. Next we’ll define a task which controls how Browsersync will work.

1
2
3
4
5
gulp.task('browser-sync', function() {
  browserSync.init({
    proxy: "192.168.33.21"
  });
});

Once added, you can type gulp browser-sync into the terminal to start a server. You should see something like the image below.

There are four separate URLs there, here’s what they mean:

  • Local: The local URL is where you can reach the server on the machine you’re running it on. In our cases you can use 192.168.33.21 or you can use the one provided by Borwsersync.
  • External: This is the URL you can use on any device connected to the network to reach the website. It will work on your local machine, your phone, tablet and so on.
  • UI: This URL points to the options for the currently running server. You can see connections, set up network throttling, view history or sync options.
  • External UI: This is the same as the UI, but accessible from any device on the network.

Why Use Browsersync?

Now that we’re done with this phase you might be thinking: why use Browsersync at all? The URL 192.168.33.21 can also be reached from any device. While this is so, you would need to install WordPress to this URL.

I usually use virtualhosts and have domains like wordpress.local or myproject.dev. These resolve locally so you can’t visit wordpress.local on your mobile phone and see the same result as on your local computer.

So far so good, we now have a test site which can be accessed from any device on the network. Now it’s time to go global and broadcast our work over the internet.

Using ngrok To Share Our Localhost

ngrok is a tool you can use to create secure tunnels to your localhost. If you sign up (still free) you get password protected tunnels, TCP and multiple simultaneous tunnels.

Installing ngrok

Go to the ngrok download page and grab the version you need. You can run it from the folder it is in or move it to a location that allows you to run it from anywhere. On Mac/Linux you can run the following command:

1
sudo mv ngrok /usr/local/bin/ngrok

If you get an error that this location doesn’t exist, simply create the missing folders.

Using ngrok

Thankfully this part is extremely simple. Once you’re running your server via Gulp, take a look at the port it is using. In the example above, the local server is running at http://localhost:3000 which means it is using port 3000. In a new terminal tab, run the following command:

1
ngrok http 3000

This will create an accessible tunnel to your localhost, the result should be something like this:

The URL you see next to “Forwarding” is what you can use to access your website from anywhere.

Conclusion

At the end of the day we can now do three things:

  • View and work on our project locally
  • View our website via any device on the network
  • Let others view our work anywhere with a simple link

This will allow you to focus on development instead of racing to keep local and test servers in sync, migrating databases and other worrisome tasks.

If you have a different method of working locally and sharing the result, let us know!