Table des matières

Promesses

Les promesses sont disponibles dans ES6.

function faireQuelqueChose() {
    return new Promise((resolve, reject) => {
        request.get(url)
        .on('data', data => {
            resolve(data);
        })
        .on('error', reject);
    });
}
 
// ...
 
faireQuelqueChose()
.then(data => {
    // traiter les données.
})
.catch(err => {
    // gérer l'erreur
});

Exemple avec reduce()

function methodThatReturnsAPromise(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log(`Processing ${id}`);
      resolve(id);
    }, 1000);
  });
}
 
let result = [1,2,3].reduce( (accumulatorPromise, nextID) => {
  return accumulatorPromise.then(() => {
    return methodThatReturnsAPromise(nextID);
  });
}, Promise.resolve());
 
result.then(e => {
  console.log("Resolution is complete! Let's party.")
});

Source

unhandledRejection

If you have to debug a huge codebase, and you don't know which Promise can potentially hide an issue, you can use the unhandledRejection hook. It will print out all unhandled Promise rejections.

process.on('unhandledRejection', (err) => {  
  console.log(err)
})