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
Promise
  .resolve({ data: 'this is some data', fail: false })
  .then(data => {
    /**
     * 1. uncoment data.fail = true observe how we end up with a swallowed error!
     * 2. comment doAsync and uncomment return doAsync, we can handle errors better and control flow
     * 3. play commenting and uncommenting lines to observe how async code can be tricky when
     * promises are not returned,
     * lines to play with:
     * 12, 13, 14, 19, 20, 54, 55
     */
    // data.fail = true
    // doSyncstuff(data)
    // doAsyncStuff(data) // swallowed error
    return doAsyncStuff(data) // rejection/throw is handled by the next catch
  })
  .catch((err) => {
    console.log('we failed!', err)
    // doSyncstuff(data)
    err.bap.bop
    if (!err.recoverable) { // we can explicitly go to the next catch by throwing or Promise.reject
      throw new Error("We Can't Recover!")
    }
    // we can recover
    return err.data // this information wil go to the next .then
  })
  .then(data => {
    console.log('all is well', data)
    return doAsyncStuff(data)
  })
  .then(data => {
    console.log('all is well 2', data)
    return doAsyncStuff(data)
  })
  // if al promises were returned on the previous blocks, this catch will handle any previously unhandled promises code
  .catch(err => { // the last catch will always catch any unhandled synchronous errors
    console.log(err) // was this expected?
    console.error('This is fatal!')
  })
// continue then/catch chain as needed


function doAsyncStuff(data) {
  if (data.fail) {
    console.log('we are failing inside doAsyncStuff!')
    return Promise.reject({ err: new Error('Failed Stuff'), data, recoverable: false })
  }
  // console.pop.bab // this will throw a synchronous error
  return Promise.resolve(data)
}


function doSyncstuff(data) {
  console.pop.bab // this will throw a synchronous error
  // throw new Error('lols'); // as well as this
  return data;
}
Babel Compiler v6.4.4 Copyright (c) 2014-2015 Sebastian McKenzie