Let me share what I learnt working here at Oodles Technologies.
Let us take an example.
Let there are four functions functionCall, doSomeworkOne, doSomeworkTwo, doSomeworkTwo and they are performing some IO tasks.
function doSomeworkThree functionCall depends doSomeworkOne, doSomeworkOne depends doSomeworkTwo, doSomeworkTwo depends doSomeworkThree. To make these sync, callback function passed as parameter in all functions.
function functionCall(data, callback){
...........
...........
doSomeworkOne(data, callback);
}
function doSomeworkOne(data, callback){
...........
...........
doSomeworkTwo(otherData, callback);
}
function doSomeworkTwo(otherData, callback){
...........
...........
doSomeworkThree(otherData, callback);
}
<span style="font-size:16px;"><span style="font-family:arial,helvetica,sans-serif;"> function doSomeworkThree(otherData, callback){
...........
...........
callback(result);
}
</span></span>
function callback(data){
return data
}
Callback, on the other hand is good. The main problem with callbacks is: nested inside of callbacks, nested inside of callbacks. In nested callbacks, it is very tough to test/maintain the codes.
Here the Promises comes. Promises provide us with a cleaner and more robust way of handling async code. Instead of using a callback. And also handling errors with promises is very easy.
function functionCall(data){
doSomeworkOne(data).then(function(data){
return doSomeworkTwo(data);
}).then(function(data){
return doSomeworkThree(data);
}).catch(function(e) {
// error handle
});
}
function doSomeworkOne(data){
retrun new Promise(function(resolve, reject){
...........
...........
if(error){
reject(error);
}else{
resolve(success);
}
})
}
function doSomeworkTwo(data){
retrun new Promise(function(resolve, reject){
...........
...........
if(error){
reject(error);
}else{
resolve(success);
}
})
}
function doSomeworkThree(data){
retrun new Promise(function(resolve, reject){
...........
...........
if(error){
reject(error);
}else{
resolve(success);
}
})
}
Note: Promises and Callbacks are not fundamentally different. Promises is advisable in nested callbacks where you want to perform a series of actions.
I hope this will help you.
Thanks.