main.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
61
62
function run(gen, ...args) {

    let it = gen(...args);

    let next;

    try {
        next = it.next();
        return handleValue(next);
    } catch (err) {
        return Promise.reject(err);
    }

    function handleErr(err) {
        return Promise.resolve(it.throw(err)).then(handleValue);
    }


    function handleValue(next) {
        if (!next.done) {
            return Promise.resolve(next.value).then(nextStep, handleErr);
        } else {
            return Promise.resolve(next.value);
        }
    }

    function nextStep(value) {
        next = it.next(value);
        return handleValue(next);
    }
}

const url = 'https://jsonplaceholder.typicode.com/users/1';
const url2 = 'https://jsonplaceholder.typicode.com/posts/1';

// async await
const load2 = async () => {
    const users = await fetch(url)
    const posts = await fetch(url2)    
    return {
      users: await users.json(),
      posts: await posts.json(),
    }
}

load2()
  .then(console.log);


// generator
run(function * (){
    const users = yield fetch(url)
    const posts = yield fetch(url2)    
    return {
      // yield something after the return keyword is allowed
      // because first the object is built and then is returned
      users: yield users.json(),
      posts: yield posts.json(),
    }
}).then(console.log);

// https://github.com/jfet97/ydkjs-Exercises/blob/master/run.js
Babel Compiler v6.4.4 Copyright (c) 2014-2015 Sebastian McKenzie