Jake Archibald (http://jakearchibald.com/2014/es7-async-functions/)
Traditional control flow:
from requests import get
location = get('http://www.telize.com/geoip').json()
lat = location['latitude']
lon = location['longitude']
weather = get('http://api.openweathermap.org/data/2.1/find/city?lat=' + str(lat) + '&lon=' + str(lon) + '&cnt=1').json()
print weather['list'][0]['weather'][0]['description']
var get = require('request').get;
get({ url: 'http://www.telize.com/geoip', json: true }, function (e, r, loc) {
var weatherUrl = 'http://api.openweathermap.org/data/2.1/find/city?lat='
+ loc['latitude'] + '&lon=' + loc['logitude'] + '&cnt=1';
get({ url: weatherUrl, json: true }, function (e, r, weather) {
console.log(weather['list'][0]['weather'][0]['description']);
});
// as get didn't block, I could do something else here at the same time
// as the weather is fetched
});
// or here
var get = require('q-io/http').read;
var getLocation = get('http://www.telize.com/geoip');
var getWeather = getLocation.then(function (location) {
location = JSON.parse(location);
return get('http://api.openweathermap.org/data/2.1/find/city?lat='
+ location['latitude'] + '&lon=' + location['logitude'] + '&cnt=1');
});
getWeather.then(function (weather) {
weather = JSON.parse(weather);
console.log(weather['list'][0]['weather'][0]['description']);
}).done();
var get = require('q-io/http').read; async function printWeather () { var location = JSON.parse(await get('http://www.telize.com/geoip')); var weather = JSON.parse(await get( 'http://api.openweathermap.org/data/2.1/find/city?lat=' + location['latitude'] + '&lon=' + location['logitude'] + '&cnt=1' )); console.log(weather['list'][0]['weather'][0]['description']); }
Promise.prototype.done = function (callback, errback) {
var promise = callback || errback ? this.then(callback, errback) : this;
promise.then(null, function (error) {
throw error;
});
};
var coro = require('coro'),
get = require('q-io/http').read;
coro.run(function * () {
var location = JSON.parse(yield get('http://www.telize.com/geoip'));
var weather = JSON.parse(yield get(
'http://api.openweathermap.org/data/2.1/find/city?lat=' +
location['latitude'] + '&lon=' + location['logitude'] + '&cnt=1'
));
console.log(weather['list'][0]['weather'][0]['description']);
}).done();
--harmony
flag, and in Chrome if you enable it.