Skip to content
This repository has been archived by the owner on Oct 7, 2020. It is now read-only.

Latest commit

 

History

History
61 lines (46 loc) · 1.24 KB

File metadata and controls

61 lines (46 loc) · 1.24 KB

Use Case #5

Name: Recursive Promise waiting can result in Node.js exiting.

Reference: https://gist.github.com/martinheidegger/4c2b7908005f65f9a53b25d5fec65f63, nodejs/help#744

Consider the following code

'use strict'

var all = {
  a: ['b', 'c'],
  b: ['d'],
  c: ['a'], // <- recursive
  d: []
}

var cache = {}

function getDeep (key) {
  var promise = cache[key]
  if (promise) {
    return promise
  }
  console.log(`Examining ${key}`)
  promise = new Promise((resolve, reject) => {
    setImmediate(() => {
      Promise.all(all[key].map(getDeep)).then(resolve).catch(reject)
    })
  })
  cache[key] = promise
  return promise
}

getDeep('a').then(allDeps => {
  console.log(`All dependencies of 'a': ${allDeps}`)
}).catch(e => console.log(e.stack || e))

//
// This will output something like:
//
//   Examining a
//   Examining b
//   Examining c
//   Examining d
//

What happens

Node.js exits without fully waiting on everything

Why it happens

At one point, a will wait on the result of a, there are no background jobs running, Node.js exits.

What can we maybe do better

  • Provide a warning when a Promise chain eventually waits on itself.
  • A Promise which gets two .then() handlers is a good indication for this.