Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ilmsg/5719779 to your computer and use it in GitHub Desktop.
Save ilmsg/5719779 to your computer and use it in GitHub Desktop.
the basics of programming with callbacks:
structure:
function simple1(cb) // the last argument is callback function
{
if(cb)return cb();// the return is required to prevent continuation of the function
}
to make a function asynchronous: add cb as last argument.
put at the end: if(cb)return cb();
callback function:
simple form:
function(data){}
standard form:
function(error,data){} // if no error. error usually contains null or maybe undefined
// with null as error
function simple2(a,b,cb)
{
if(b==0) return cb(new Error('error description'));
var data=a/b;
if(cb)return cb(null,data);
}
usage:
//
simple2(1, 3, function(err,data) {
if(error){
throw error;
// or do something else like
console.log(error.stack)
return;
}
console.log('data=',data)
});
passing the callback on to next function:
function simple3(a,b,cb)
{
a++;
return simple2(a,b,cb);
}
using anonymous function to pass arguments as closure:
function simple3(a,b,cb)
{
var preva=a;
a++;
return simple2(a,b,function(e,data){ if(cb) cb(e,data,preva)});
}
//use the name cb all over the place and it just works:
var async=require('async')
var items=[1,2,3]
function calc(a,cb)
{
cb(a*a)
}
function simple4(items,cb)
{
var results={};
async.eachLimit(Object.keys(items),4,function(k,cb)
{
var item=items[k]
result[k]=calc(item,cb)
},function(){
console.log('done all');
cb(results);
});
}
// a short cut cb
function simple5(items,cb1)
{
var results={};
function cb(){cb1(results)} // sometimes people call the function next instead of cb
async.eachLimit(Object.keys(items),4,function(k,cb)
{
var item=items[k]
result[k]=calc(item,cb)
},function(){
console.log('done all');
cb();
});
}
//while loop:
function simple6(times,cb)
{
function loop()
{
times--;
if(times==5)return loop();// use return iterator() as continue
// do something here
if(times>0)return loop(); else return cb()// use return cb() as break
}
if(times>0)loop(); else cb()
}
// retry
//from this:
function simple7(options,cb)
{
do_async_request(options,function(err,data){
if(err){
console.log('simple7 - error, faild',err.stack,options);
return;
}
//do work with data
})
}
//to this:
function simple7_with_retry(options,cb)
{
var retries=0;
function retry()
{
do_async_request(options,function(err,data){
if(err){
if(retries<7)
{
retries++;
console.log('simple7 - error, retrying',err.stack,options);
setTimeout(retry,3000)
return;
}
else {
console.log('simple7 - error, faild',err.stack,options);
return;
}
}
//do work with data
})
}
retry()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment