javascript - Using promises to return the result of an asynchronous function as a 'variable' -


i'm having trouble asynchronous execution in nodejs. in particular, have many use cases want use result of asynchronous request later in code, , don't want wrap whole thing in level of indentation such async.parallel.

i understand solution using promises, struggling implementation right , resources have tried aren't helping.

my current problem this: need _id of mongodb document when inserted. have switched using mongojs using official mongodb driver made aware mongojs not support promises. assist providing basic example of how return value using promises?

thanks again.

with node.js driver, use collection's insert() method returns promise. following example demonstrates this:

var db = require('mongodb').db,     mongoclient = require('mongodb').mongoclient,     server = require('mongodb').server;     var db = new db('test', new server('localhost', 27017));  // fetch collection insert document db.open(function(err, db) {     var collection = db.collection("post");      // create function return promise     function getpostpromise(post){         return collection.insert(post);     }      // create post insert     var post = { "title": "this test" },         promise = getpostpromise(post); // promise calling function      // use promise log _id        promise.then(function(posts){         console.log("post added _id " + posts[0]._id);         }).error(function(error){         console.log(error);     }).finally(function() {         db.close();     });  }); 

you can use mongoose's save() method returns promise. basic example demonstrate follows:

// test.js var mongoose = require('mongoose'),     schema = mongoose.schema;  // establish connection mongoose.connect('mongodb://localhost/test', function(err) {     if (err) { console.log(err) } });  var postschema = new schema({     "title": string });  mongoose.model('post', postschema);  var post = mongoose.model('post');  function getpostpromise(posttitle){     var p = new post();     p.title = posttitle;     return p.save(); }  var promise = getpostpromise("this test"); promise.then(function(post){     console.log("post added _id " + post._id);   }).error(function(error){     console.log(error); }); 

run app

$ node test.js post added _id 5696db8a049c1bb2ecaaa10f $ 

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -