Skip to content

Instantly share code, notes, and snippets.

@isaacs
Forked from tlrobinson/2-async.js
Created February 3, 2010 22:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save isaacs/294109 to your computer and use it in GitHub Desktop.
Save isaacs/294109 to your computer and use it in GitHub Desktop.
// EXAMPLE 1: async response
// PSGI equivalent
var app = function(env) {
return function(respond) {
// do some event stuff
setTimeout(function() {
respond({ status : code, headers : headers, body : body });
}, 1000);
}
}
// AJSGI
var app = function(env) {
return { then : function(respond) {
// do some event stuff
setTimeout(function() {
respond({ status : code, headers : headers, body : body });
}, 1000);
}};
}
// JSGI + Q
var app = function (env) {
var response = Q.defer();
setTimeout(function () {
response.resolve({ status: code, headers : headers, body : body });
}, 1000);
return response.promise;
};
// EJSGI
var app = function (env) {
var p = new Promise;
setTimeout(function () {
p.emitSuccess({status:code, headers:headers, body:body});
}, 1000);
return p;
};
// EXAMPLE 2: async response + streaming body asynchronously
// PSGI equivalent
var app = function(env) {
return function(respond) {
var w = respond({ status : code, headers : headers });
// do more event stuff
setTimeout(function() { w.write(body); }, 1000);
setTimeout(function() { w.close(); }, 2000);
}
}
// AJSGI
var app = function(env) {
return { then : function(respond) {
// do some event stuff
respond({ status : code, headers : headers, body : { forEach : function(write) {
return { then : function(close) {
setTimeout(function() { write(body); }, 1000);
setTimeout(function() { close(); }, 2000);
}};
}});
}};
}
// JSGI + Q
var app = function (env) {
var response = Q.defer():
response.resolve({status: code, headers: headers, body: {
"forEach": function (write) {
var done = Q.defer();
setTimeout(function() { write(body); }, 1000);
setTimeout(function() { done.resolve(); }, 2000);
return done.promise;
}
}});
return response.promise;
};
// EJSGI
var app = function (env) {
var p = new Promise;
setTimeout(function () {
var s = new (env.jsgi.stream);
p.emitSuccess({status:code, headers:headers, body:s});
s.write(body);
s.close();
}, 1000);
return p;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment