mardi 31 mars 2015

Find inside callback of another find (...), how to escape from callback hell?

(First: I'm sorry, I don't speak english very well!)


I wanna return the results of 3 finds in one array. My code (next) is running well, but I'm in callback hell!





_Schema
.static('retrieveAll', function(cb) {
query = {};
this.find(query, function(err, data) {
if(err) {
cb(err, null);
return;
}

if(data)
all = data;
else
all = [];

_StoresModel.find(query).select('contact address').exec(function(err, data) {
if(err) {
cb(err, null);
return;
}

if(data) {
all = data.reduce(function(coll, item) {
coll.push(item);
return coll;
}, all);
}

_CustomersModel.find(query).select('contact address').exec(function(err, data) {
if(err) {
cb(err, null);
return;
}

if(data) {
all = data.reduce(function(coll, item) {
coll.push(item);
return coll;
}, all);
}

cb(null, all);
});
});
});
});



I've a FIND inside a FIND inside a FIND. Is there anyway to improve this?


Aucun commentaire:

Enregistrer un commentaire