On Github chrishiestand / slides-2016-02-02-js-async-awaitier
by Chris Hiestand @dimmer
import _Isofetch from 'isomorphic-fetch'; async function getIp_P() { let ip = await fetch('https://api.ipify.org?format=json') .then((response) => { return response.json(); }); return ip; } function main() { [1,2,3].map(async () => { console.log('wan ip:'); console.log(await getIp_P()); }); } main();
Output
wan ip: wan ip: wan ip: { ip: '1.2.3.4' } { ip: '1.2.3.4' } { ip: '1.2.3.4' }
async function main() { return 'hello, wait for it, world'; } console.log(main());
Output
Promise { _d: { p: [Circular], c: [], a: undefined, s: 1, d: true, v: 'hello, wait for it, world', h: false, n: true } }
var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator'); var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } let main = function () { var ref = (0, _asyncToGenerator3.default)(function* () { return 'hello, wait for it, world'; }); return function main() { return ref.apply(this, arguments); }; }(); console.log(main());
Promises return immediately but settle eventually
async function blah() { let foo = await doStuff_P(); //more stuff return foo; } function main() { blah(); //returns promise immediately }
import _Isofetch from 'isomorphic-fetch'; import _Promise from 'bluebird'; async function getIp_P() { let ip = await fetch('https://api.ipify.org?format=json') .then((response) => { return response.json(); }); return ip; } function main() { _Promise.map([1,2,3], async () => { console.log('wan ip:'); console.log(await getIp_P()); }, {concurrency: 1}); } main();
Output
wan ip: { ip: '1.2.3.4' } wan ip: { ip: '1.2.3.4' } wan ip: { ip: '1.2.3.4' }
import _Isofetch from 'isomorphic-fetch'; async function getIp_P() { let ip = await fetch('https://api.ipify.org?format=json') .then((response) => { return response.json(); }); return ip; } async function main() { let i = 0; while( i < 3 ) { console.log('wan ip:'); console.log(await getIp_P()); i++; } } main();
Output
wan ip: { ip: '1.2.3.4' } wan ip: { ip: '1.2.3.4' } wan ip: { ip: '1.2.3.4' }
Async ⊧ Promise
Iterable + Async love with:
await Promise.map([1,2,3], remote_P)
Related blog post at: http://goo.gl/9J2S5V