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
const tasks = [
  { name: 'task-1', time: 200 },
  { name: 'task-2', time: 400},
  { name: 'task-3', time: 10},
  { name: 'task-4', time: 600}
];

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;
}

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

executeTasks(tasks);

node v9.7.1 linux/amd64