- Modern JavaScript Web Development Cookbook
- Federico Kereki
- 335字
- 2021-07-02 14:49:57
Getting started
Let's see both styles by using a simple example. This book was written in three different cities: Pune, India; London, England; and Montevideo, Uruguay, so let's do some work related to those cities. We will write code that will get weather information for those cities:
- For Montevideo alone
- For London and then for Pune, in series, so that the second call won't start until the first is done
- For the three cities in parallel, so that all three requests will be processed at the same time, gaining time by the overlap
We will not get into details such as using this or that API, getting a private key, and so on, and we'll just fake it by accessing the free The Weather Channel page. We will use the following definitions for all our coding, which we'll do in Node, using the axios module; don't worry about the details now:
// Source file: src/get_service_with_promises.js
const axios = require("axios");
const BASE_URL = "https://weather.com/en-IN/weather/today/l/";
// latitude and longitude data for our three cities
const MONTEVIDEO_UY = "-34.90,-56.16";
const LONDON_EN = "51.51,-0.13";
const PUNE_IN = "18.52,73.86";
const getWeather = coords => axios.get(`${BASE_URL}${coords}`);
The BASE_URL constant provides the basic web address, to which you must attach the coordinates (latitude, longitude) of the desired city. On its own, we would get a page like the one shown in the following screenshot:
In real life, we would not be getting a web page but rather an API, and then process the returned results. In our case, since we don't actually care for the data, but for the methods we'll use to do the calls, we'll be content with just showing some banal information, such as how many bytes were sent back. Totally useless, I agree, but this is enough for our example!