Advertisement
Guest User

Untitled

a guest
Sep 20th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. const Bluebird = require('bluebird');
  2. const fs = require('fs');
  3.  
  4. // Run multiple promises at once and get their values
  5. Bluebird
  6. .join(
  7. runPromise1(),
  8. runPromise2(),
  9. runPromise3()
  10. )
  11. .spread((promise1result, promise2result, promise3result) => {}) // Know .spread() is used when .then()ing multiple values with .join
  12.  
  13. // Convert a callback to a promise
  14. function readFilePromise(path) {
  15. return new Bluebird((resolve, reject) => {
  16. fs.readFile(path, 'utf-8', (err, data) => {
  17. if (err) return reject(err);
  18. return resolve(data);
  19. })
  20. })
  21. }
  22.  
  23. // Iterate over a collection of items asynchronously, but not necessarily in order
  24. const collection = [
  25. {id: 1, name: 'Wes'},
  26. {id: 2, name: 'Jacob'},
  27. {id: 3, name: 'Nicky'}
  28. ];
  29. Bluebird.map(collection, person => {
  30. return savePromise(person);
  31. })
  32.  
  33. // Iterate over a collection of items asynchronously, and in order
  34. Bluebird.reduce(collection, (accumulator, person) => {
  35. return savePromise(person)
  36. .then(result => {
  37. accumulator.push(result);
  38. return accumulator;
  39. })
  40. }, [])
  41.  
  42. // Know that you can continue chaining values with .then, even if you're not returning a promise
  43. callAsyncPromise()
  44. .then(result => {
  45. if (!result) {
  46. throw new Error('wtf something happennnnned');
  47. }
  48. return 'success';
  49. })
  50. .then(status => {
  51. console.log(status) // This will console.log as 'success';
  52. return 'continued';
  53. })
  54. .then(status => {
  55. console.log(status); // This will console.log as 'continued'
  56. })
  57.  
  58. // Know to use throw to reject execution of the current promise chain
  59.  
  60. callAsyncPromise()
  61. .then(result => {
  62. throw new Error('We want to end the promise chain.');
  63. })
  64. .catch(error => {
  65. console.log(error.message) // console.log reads as "We want to end the promise chain"
  66. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement