Skip to content

Instantly share code, notes, and snippets.

@paxperscientiam
Created May 14, 2017 18:01
Show Gist options
  • Select an option

  • Save paxperscientiam/23088fc0209be8fa015447c4a2c56bef to your computer and use it in GitHub Desktop.

Select an option

Save paxperscientiam/23088fc0209be8fa015447c4a2c56bef to your computer and use it in GitHub Desktop.
promise chain example
// thanks to @kakashiAL from #node.js on freenode
function getDataA(data) {
return new Promise (function(res,rej) {
res(data);
})
}
function getDataB(data) {
return new Promise (function(res,rej) {
var x = [data,data,data]
console.log(x);
res(x);
})
}
function getDataC(data) {
return new Promise (function(res,rej) {
var x = data[0];
console.log(x);
res(x);
})
}
function getDataD(data) {
return new Promise (function(res,rej) {
var x = data + data;
console.log(x);
res(x);
})
}
// getDataA is a function that gets data from a database/network/file
// it returns a promise
// everything what returns a promise has the method then() and catch()
getDataA('Hi')
.then(dataA => {
// getDataB also returns a promise
// it data is only available in the next then function
// we have to return it to be able to get its data in the next then()
return getDataB(dataA);
}).then(dataB => {
return getDataC(dataB);
}).then(dataC => {
return getDataD(dataC);
}).catch(error => {
// ERROR HANDLING HERE
console.log("you have an error: ", error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment