[英]Promises with _.each async calls
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);
}
});
});
});
}
}
我想返回一個promise之類的東西,這將確保在我完成所有的每次調用(即進行了asyn searchMovie調用)后,然后可以使用.then()從要存儲在其中的數據庫中檢索內容碼。 我是新來的諾言,不知道該怎么做。 我有一個調用indexMovie函數的控制器,一旦調用結束,我想從數據庫中檢索保存的值。
使用Promise.each
而不是_.each
來等待異步操作。 如果操作不相關,請改用Promise.map
以便它們可以並行執行。
首先-正確的解決方案是使您的數據庫調用批量執行查詢,而不是對API進行100次查詢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);
}
});
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.