3

when I do console.log(all) I expect to get back the filtered sorted data but instead I get back the whole original data. why?

var Comp = require("./models/company.js");
  var arr = [
    {name : "comp1",industry : "industry1", ranking: 20},
    {name : "comp2",industry : "industry2", ranking: 5},
    {name : "comp3",industry : "industry3", ranking: 10}
  ]



var output = {};  
var promise = Comp.find({}).exec()
  promise.then(function(docs){
        return Comp.remove({}).exec()

    })
    promise.then(function(){
            console.log("deleted")
        })
    promise.then(function(){
        return Comp.create(arr).exec()

    })
    promise.then(function(data){
        output.data = data;
        console.log(output)
    })
    promise.then(function(){
        return Comp.find({}, 'name -_id ranking', {sort :{ranking :1}}).exec();
    })
    promise.then(
        function(all){
            console.log("test")
            console.log(all)
        },
        function(error){
            console.log(error)
        }
    )
    promise.then(function(){
        return Comp.count({}, function(count){
            return count;
        });
    })
    promise.then(function(count){
        console.log("count")
        // console.log(count)
    })

my other related question.

Community
  • 1
  • 1
jack blank
  • 5,073
  • 7
  • 41
  • 73

1 Answers1

2

You're attaching all the .then callbacks to the same promise. That's not chaining, but branching.

Branch:

var p = Promise.resolve(1);
p.then(foo);
p.then(bar); // wont wait for foo. Calls bar(1).

To chain, always attach to the last promise.

Chain:

var p = Promise.resolve(1);
p = p.then(foo);
p = p.then(bar); // waits for foo. Calls bar(result_from_foo).

or simply: Promise.resolve().then(foo).then(bar);

Community
  • 1
  • 1
jib
  • 40,579
  • 17
  • 100
  • 158