Files
  • index.js
index.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
63
const tasks = [
  {
    name: 'task-1',
    time: 200
  },
  {
    name: 'task-2',
    time: 400
  },
  {
    name: 'task-3',
    time: 100
  },
  {
    name: 'task-4',
    time: 50
  }
];



function executeTasks(tasks) {
  return tasks.reduce((accumulator, task) => {
    return accumulator.then(() => getPromise(task));
  }, Promise.resolve());
}

// executeTasks(tasks);

function getPromise(task) {
  const taskPromise = new Promise((resolve, reject) => {
    console.log(task.name + " started.");
    
    setTimeout(() => {
      console.log(task.name + " done in ", task.time, "ms.");
      resolve(task.name);
    }, task.time);
  });
  
  return taskPromise;
}

// Type 1
function promiseReturnsPromise() {
  return Promise.resolve().then(function (){
    return getPromise(tasks[0]);
  }).then(function () {
    return getPromise(tasks[1]);
    });
}

promiseReturnsPromise();

// Type 2
function promiseDoesnotReturn() {
  Promise.resolve().then(function (){
    getPromise(tasks[0]);
  }).then(function () {
    getPromise(tasks[1]);
    });
}

// promiseDoesnotReturn()
node v10.15.2 linux/amd64