Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Bluebird = require('bluebird');
- const fs = require('fs');
- // Run multiple promises at once and get their values
- Bluebird
- .join(
- runPromise1(),
- runPromise2(),
- runPromise3()
- )
- .spread((promise1result, promise2result, promise3result) => {}) // Know .spread() is used when .then()ing multiple values with .join
- // Convert a callback to a promise
- function readFilePromise(path) {
- return new Bluebird((resolve, reject) => {
- fs.readFile(path, 'utf-8', (err, data) => {
- if (err) return reject(err);
- return resolve(data);
- })
- })
- }
- // Iterate over a collection of items asynchronously, but not necessarily in order
- const collection = [
- {id: 1, name: 'Wes'},
- {id: 2, name: 'Jacob'},
- {id: 3, name: 'Nicky'}
- ];
- Bluebird.map(collection, person => {
- return savePromise(person);
- })
- // Iterate over a collection of items asynchronously, and in order
- Bluebird.reduce(collection, (accumulator, person) => {
- return savePromise(person)
- .then(result => {
- accumulator.push(result);
- return accumulator;
- })
- }, [])
- // Know that you can continue chaining values with .then, even if you're not returning a promise
- callAsyncPromise()
- .then(result => {
- if (!result) {
- throw new Error('wtf something happennnnned');
- }
- return 'success';
- })
- .then(status => {
- console.log(status) // This will console.log as 'success';
- return 'continued';
- })
- .then(status => {
- console.log(status); // This will console.log as 'continued'
- })
- // Know to use throw to reject execution of the current promise chain
- callAsyncPromise()
- .then(result => {
- throw new Error('We want to end the promise chain.');
- })
- .catch(error => {
- console.log(error.message) // console.log reads as "We want to end the promise chain"
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement