承诺与每个asynchronous调用

var TheMovieDb = require('themoviedb'); var moviedbClient = new TheMovieDb('*****'); var movieJson = require("./seedMovieDB/movieName.json"); var MovieEntry = require('./movie.model'); var movieApi = new TheMovieDb('1b3819c5f61aaef99edf4c47a5de46f4', 'en'); var P = require('bluebird'); var _ = require('underscore'); var moviedb = module.exports = { indexMovie : function indexMovie(){ MovieEntry.removeAsync({}) .then (function() { _.each(movieJson, function(val, key, cb){ movieApi.searchMovies(val.name).then (function(mDetails) { if(mDetails !== undefined){ _.each(mDetails , function(val, key, cb){ var m = new MovieEntry({ id: val.id, title : val.title, originalTitle : val.originalTitle, year : val.year, popularity : val.popularity, voteAverage : val.voteAverage, votes : val.votes, isAdult : val.isAdult, video : val.video, poster : val.poster, backdrop : val.backdrop, }); m.save(function(err, movie_saved){ if(err){ console.log(err); }else{ console.log("saved"); } }); }) } }).catch(function(err){ if(err){ console.log(err); } }); }); }); } 

}

我想返回一个承诺或什么,这将确保一旦我所有的每一个电话,这是asyn searchMovie调用所做的,结束,然后我可以使用.then()从我存储的数据库中检索的东西码。 我对承诺是新的,不知道如何去做。 我有一个调用indexMovie函数的控制器,一旦调用结束,我想从数据库中检索保存的值。

使用Promise.each而不是_.each来等待asynchronous操作。 如果操作不相关,请使用Promise.map以便它们可以同时执行。

首先 – 正确的解决scheme是让你的数据库调用批量执行查询,而不是查询100次的API 100次,查询一次。 movieApi.searchMovies(val.name)应该有一个可用于多个值的movieApi.searchMovies(...arrr)替代方法,依此类推。

这就是说,主要部分变成:

 return Promise.map(movieJson, x => searchMovies(x.name)).map(x => new MovieEntry(val); ).map(x => x.save() ).then(x => console.log("All Done!") ).catch(e => { console.error("Error somewhere", e); throw e; }); 

只需添加promise()。done(function(){在每个结尾

 var moviedb = module.exports = { indexMovie : function indexMovie(){ MovieEntry.removeAsync({}) .then (function() { _.each(movieJson, function(val, key, cb){ movieApi.searchMovies(val.name).then (function(mDetails) { if(mDetails !== undefined){ _.each(mDetails , function(val, key, cb){ var m = new MovieEntry({ id: val.id, title : val.title, originalTitle : val.originalTitle, year : val.year, popularity : val.popularity, voteAverage : val.voteAverage, votes : val.votes, isAdult : val.isAdult, video : val.video, poster : val.poster, backdrop : val.backdrop, }).promise().done(function(){ //the stuff you need }); m.save(function(err, movie_saved){ if(err){ console.log(err); }else{ console.log("saved"); } }); }) } }).catch(function(err){ if(err){ console.log(err); } }); }); }); }