I am wondering how to accomplish sharing values between "chain links" in Q promises without totally botching the pretty idiom of promises.
I am using Q to do some logic on mongo databases. My GET
endpoint logic looks great:
return Q.ninvoke(this.db, 'collection', 'namespace')
.then(function(namespaceCollection){
return Q.ninvoke(namespaceCollection,'findOne',{"name":name})
}).then(function(queryResults){
if(!queryResults){
throw new providerErrors.NotFound();
return
}
return queryResults;
},function(err){
throw new providerErrors.BadRequest();
});;
Applying the same pattern to my insert endpoint however, I run into a problem. I have to use the collection returned from the first promise, the one that gets the collection off the db object, in order to save the value back down:
return Q.ninvoke(this.db,'collection','namespace')
.then(function(namespaceCollection){
return Q.ninvoke(namespaceCollection,findOne,{"name":namespace.name});
})
.then(function(foundNamespace){
if(namespace){
throw new providerErrors.Conflict();
return
}
//This is a new namespace object, give it a datetime and then
//let's save it!
namespace.createDate = new Date();
})
.then(function(namespaceToSave){
//uhoh! no collection in scope down here, just the value to persist!
})
I'm wondering what's the best, most idiomatic way to solve this problem. I explored Q.all
as a possible solution, but this obviously would not ensure the sequence of events.