0

These are my code.

var myOrderIds = req.user.orders; // array of order document's ObjectId
var myReserv = []; // I want to put specific order into myRerv[] by mongoose findOne()

var showReservList = function(oids, callback) {
    oids.forEach(function(oid) {
        database.OrderModel.findOne({'_id' : oid, 'isCompleted' : false},function(err, docs) {
             callback(docs);
        });
    });
}

showReservList(myOrderIds, function (res) {
    myReserv.push(res);
});

console.log(myReserv); // empty

The problem is myReserv[] is empty. I wonder how to consolidate multiple asynchronous processes and not just handle the completion of a single one. (This is the common case.) console.log(myReserv) is executed faster than myRserv.push(res). I want to delay console.log(myRresrv) until myRserv.push(res) finishes to work.

조민주
  • 3
  • 4
  • Show your attempt with Promises, because they do work if used correctly. – Carcigenicate Aug 10 '17 at 12:38
  • This is a synchronicty issue. Synchonous code (like `console.log()`) will always execute before asynchronous code completes. I assume your `findOne()` method returns a promise, thus is asynchronous. – Mitya Aug 10 '17 at 12:38
  • `myReserv` isn't undefined. It's explicitely an empty array at the moment it's being logged. – Jeremy Thille Aug 10 '17 at 12:41
  • IMO, the 'duplicate' mark on this question is improper considering how the bigger part of this issue concerns how to consolidate multiple asynchronous processes and not just handle the completion of a single one (which is the case with the linked question) – Lennholm Aug 10 '17 at 12:46
  • @MikaelLennholm Thank you! I edited my question properly. – 조민주 Aug 10 '17 at 16:03

0 Answers0