Skip to content

Instantly share code, notes, and snippets.

@0xKayvan
Created February 27, 2018 18:02
Show Gist options
  • Save 0xKayvan/4cdd265ab27820fc086e2ae2a4592a7d to your computer and use it in GitHub Desktop.
Save 0xKayvan/4cdd265ab27820fc086e2ae2a4592a7d to your computer and use it in GitHub Desktop.
var Promise = require('bluebird');
doTask1()
.then(doTask2)
.then(doARecursiveTask)
.then(doFinalTask)
.then(function (fullfilled) {
console.log('that last thing is:', fullfilled)
console.log('[DOOOOOOOOONEEEE]')
})
.catch(function(err) {
console.log('just got error')
})
function doTask1() {
return new Promise(function (resolve, reject) {
console.log('task 1 is done')
resolve('some data from task 1')
})
}
function doTask2(fullfilled) {
return new Promise(function (resolve, reject) {
console.log('task 2 recieved:', fullfilled)
console.log('task 2 is done')
resolve('some data from task 2')
})
}
function doARecursiveTask(fullfilled) {
var numberOfTimeRecursiveTaskShouldBeDone = 10
var numberOfTimeRecursiveTaskSoFar = 0
var condition = function() {
return numberOfTimeRecursiveTaskSoFar < numberOfTimeRecursiveTaskShouldBeDone
}
var recursiveTask = function() {
return new Promise(function(resolve, reject) {
numberOfTimeRecursiveTaskSoFar++;
console.log(numberOfTimeRecursiveTaskSoFar);
resolve('final shit');
})
}
var resolver = Promise.defer();
var loop = function() {
if (!condition()) {
//this will run and pass data to final task
return resolver.resolve('all rec was done');
} else {
return Promise.cast(recursiveTask())
.then(loop)
.catch(resolver.reject);
}
}
process.nextTick(loop)
return resolver.promise
}
function doFinalTask(fullfilled) {
return new Promise(function (resolve, reject) {
console.log('final task recieved:', fullfilled)
console.log('final task is done')
resolve('some data from final task')
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment