在渲染页面之前,我需要确保从api调用中获取的所有内容都保存到数据库中。
let saveUsersToDB = function () {
//fetch users func
return getAllUsers.then((data) => {
//save to db func
async.each(data, (user, callback) => {
//Mongoose model
let newUser = new User;
//save to db
newUser.save((err) => {
if (err) {
callback(err)
}
else {
callback('user saved');
}
})
// async.each callback
}, function (err) {
if (err) {
console.log('error');
} else {
console.log('Async each done');
}
});
});
};
我称之为:
saveUsersToDB().then(()=>{
console.log("All users saves")
})
结果是:
//All users saved
//Async each done
我无法弄清楚在then()链中保持正确顺序的正确构造。
答案 0 :(得分:0)
getAllUsers.then的回调应该返回一个promise。否则,将在getAllUsers之后立即调用saveUsersToDB.then回调。
//fetch users func
let saveUsersToDB = () => getAllUsers.then( ( data ) => new Promise( ( resolve, reject ) => {
//save to db func
async.each( data, ( user, callback ) => {
//Mongoose model
let newUser = new User();
//save to db
newUser.save( ( err ) => {
if ( err ) return callback( err );
console.log( "user saved" );
callback();
} );
// async.each callback
}, function ( err ) {
if ( err ) return reject( err );
console.log( "all users saved" );
resolve();
} );
} ) );
saveUsersToDB().then( () => console.log( "done" ) );