On Github andersjanmyr / promise-lab
Anders Janmyr http://anders.janmyr.com @andersjanmyr
function asyncHello(what, callback) {
setTimeout(function() {
callback(null, 'Hello ' + what);
}, 100);
}
asyncHello('Tapir', function(err, hello) {
if (err) return console.error('Failure');
console.log(hello);
});
function asyncFail(what, callback) {
setTimeout(function() {
callback('I fail, therefore I am');
}, 100);
}
asyncFail('Tapir', function(err, hello) {
if (err) return console.error('Failure');
// do something
});
function asyncError(what, callback) {
try {
return callback(null, JSON.parse(what));
} catch (error) {
return callback(error);
}
}
promise.then(onFulfilled, onRejected)
promise.catch(onRejected) // Same as promise.then(null, onRejected)
promise.then(onFulfilled, onRejected) .finally() // Clean up resources
function authenticate() {
return getUsername()
.then(function (username) {
return getUser(username);
})
// chained because we will not need the user name in the next event
.then(function (user) {
return getPassword()
// nested because we need both user and password next
.then(function (password) {
if (user.passwordHash !== hash(password)) {
throw new Error("Can't authenticate");
}
});
})
.catch(errorHandler);
}
// Creates a promise from a value
return Q.fcall(function () {
return 10;
});
// Interfacing with async functions
var deferred = Q.defer();
FS.readFile("foo.txt", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
});
return deferred.promise;
return Q.nfcall(FS.readFile, "foo.txt", "utf-8"); return Q.nfapply(FS.readFile, ["foo.txt", "utf-8"]);
var Kitty = mongoose.model("Kitty");
var findKitties = Q.nbind(Kitty.find, Kitty);
findKitties({ cute: true }).done(function (theKitties) {
});
return Q.all([
eventualAdd(2, 2),
eventualAdd(10, 20)
])
.then(function(resultArray);
then gets an array of results.
Q.all([getFromDisk(), getFromCloud()])
.spread(function (diskVal, cloudVal) {
assert(diskVal === cloudVal);
})
.done();
foo(initialVal).then(bar).then(baz).then(qux);
var funcs = [foo, bar, baz, qux];
//With a loop
var result = Q(initialVal);
funcs.forEach(function (f) {
result = result.then(f);
});
return result;
var funcs = [foo, bar, baz, qux];
//With reduce
return funcs.reduce(function (soFar, f) {
return soFar.then(f);
}, Q(initialVal));
// Or compact
return funcs.reduce(Q.when, Q());
// when is the static equivalent of then
return Q.when(valueOrPromise, function (value) {
}, function (error) {
});
Anders Janmyr http://anders.janmyr.com @andersjanmyr