为什么我的第一个。然后没有坚持承诺,因为它没有返回任何东西? 在以下函数中,控制台显示: blablabla ...... ID列表
暗示第二个。然后在第一个之前执行。
Model.collection().query(...).fetch().then(function(result) {
// result is a list of models.
// I want to run a promise on each of these models in order to add stuff to them
result.each(function(model) {
New promise based task on model with .then(function(r) {
console.log(model.id);
// with something like:
model.set('newvalue', r.value);
});
});
}).then(function(result) {
console.log('blablabla');
return res.json(result.toJSON());
}).catch(next);
};
答案 0 :(得分:0)
你可能想要使用Bookshelf的collection.mapThen,像这样:
SomeModel.collection().fetch()
.then(function(collection) {
// collection is a bookshelf collection object
// collection.mapThen returns a promise
return collection.mapThen(function(model) {
console.log("model " + model.id);
// we can return another promise inside here, and the .mapThen promise
// won't be resolved until this one is.
return knex('users').where({id: model.get('user_id')}).first()
.then(function(u) {
model.set('userName', u.user_name);
// return model as the result of the map.
return model;
});
})
})
.then(function(results) {
// results is a list of all the modified models
console.log('blablabla');
return res.json(results);
})
.catch(next);