Skip to content

Commit 4c04867

Browse files
committed
Async js with promises
1 parent 229bfe9 commit 4c04867

File tree

6 files changed

+80
-0
lines changed

6 files changed

+80
-0
lines changed

async-js-with-promises/README.md

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Async JavaScript with Promises
2+
3+
> [https://youtu.be/g90irqWEqd8](https://youtu.be/g90irqWEqd8)
4+
5+
Install [io.js](https://iojs.org/en/index.html).
6+
7+
Within this folder run the terminal command `npm install` to install the
8+
`devDependencies` and `dependencies`.
9+
10+
Then run `npm start` to start up a development server on `http://localhost:9966`

async-js-with-promises/bears.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
grizzly
2+
polar
3+
brown

async-js-with-promises/fetch.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
var xhr = require('xhr')
2+
3+
module.exports = function (uri) {
4+
return new Promise(function (resolve, reject) {
5+
xhr(uri, function (err, res, body) {
6+
if (err) return reject(err)
7+
if (res.statusCode !== 200) return reject(new Error(body))
8+
resolve(body)
9+
})
10+
})
11+
}

async-js-with-promises/fish.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
salmon
2+
tuna
3+
bass

async-js-with-promises/index.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
var fetch = require('./fetch.js')
2+
3+
// Using then and catch
4+
// var promise = fetch('bears.txt')
5+
//
6+
// promise.then(function (bears) {
7+
// console.log(bears)
8+
// //throw new Error('Uh oh')
9+
// return fetch('fish.txt')
10+
// }).then(function (fish) {
11+
// console.log(fish)
12+
// }).catch(function (err) {
13+
// console.error('WE GOT ERROR', err)
14+
// })
15+
16+
// Using Promise.all
17+
// Promise.all([
18+
// fetch('bears.txt'),
19+
// fetch('fish.txt'),
20+
// ]).then(function (values) {
21+
// var bears = values[0]
22+
// var fish = values[1]
23+
// console.log(bears, fish)
24+
// })
25+
26+
// Creating promises
27+
var promise = new Promise(function (resolve, reject) {
28+
//reject(new Error("uh oh"))
29+
resolve('all good')
30+
})
31+
32+
promise.then(function (result) {
33+
console.log('was it good?', result)
34+
}).catch(function (err) {
35+
console.error('ERR', err)
36+
})

async-js-with-promises/package.json

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"name": "async-js-with-promises",
3+
"version": "0.1.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"start": "budo index.js --live"
8+
},
9+
"author": "Kyle Robinson Young <[email protected]> (http://dontkry.com)",
10+
"license": "MIT",
11+
"devDependencies": {
12+
"budo": "^4.0.0"
13+
},
14+
"dependencies": {
15+
"xhr": "^2.0.2"
16+
}
17+
}

0 commit comments

Comments
 (0)