-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path08-generators-fetch.js
60 lines (52 loc) · 1.57 KB
/
08-generators-fetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
var runs = require('./lib/runs')
var axios = require('axios')
var gets = require('./lib/gets')
var puts = require('./lib/puts')
var apiRoute = 'https://bobsburger.azurewebsites.net/api/random'
function requestName () {
return new Promise(gets)
}
function fetchRandomBurgerName () {
return axios.get(apiRoute)
.then(function (res) {
return res.data
})
}
function getName (resObject) {
return resObject.name
}
/** Way 1: Promise Chain */
// puts('Enter your name: ')
// var name
// requestName()
// .then(function (personName) {
// puts('Fetch from Server...')
// name = personName
// return fetchRandomBurgerName()
// })
// .then(function (burgerNameObject) {
// var burgerName = getName(burgerNameObject)
// puts(name + ' wants a ' + burgerName)
// }).catch(err => console.log(err.message))
/** Way 2: Generators + Promises */
function * program () {
puts('Enter your name: ')
var name = yield requestName()
puts('Fetch from Server...')
var burgerNameObject = yield fetchRandomBurgerName()
puts('got something from the server')
var burgerName = getName(burgerNameObject)
puts(name + ' wants a ' + burgerName)
}
runs(program)
/** Way 3: Async/Await */
// async function program () {
// puts('Enter your name: ')
// var name = await requestName()
// puts('Fetch from Server...')
// var burgerNameObject = await fetchRandomBurgerName()
// puts(burgerNameObject)
// var burgerName = getName(burgerNameObject)
// puts(name + ' will get a ' + burgerName)
// }
// program()