我使用了很棒的Q库来支持Chrome应用中支持的IndexedDB。问题是在promise链中的所有方法完成之前调用Q.allSettled。
我有两张桌子:
自动搜索所有search_queries的方式如下:
var promises = [];
var sq_count = 0;
search_queries.foreach(function (val, index, array) {
// 1. Search Twitter Asynchronously
// 2. Then Add them to a tweets table
// 3. Then update a search queries table
promises.push(
// Call Twitter API
search_twitter(Q, val)
.then(function(tweets) {
// Add Tweets to tweets table
return (add_tweets(Q, tweets, val));
})
// Update number of tweets in search_queries table
.then(function(search_query){
// Update counts for search_search query and store it
return update_search_query_after_search(search_query);
})
.then(function(v){
console.log("Chain is completed");
)); // Close promise chain
sq_count ++;
if(sq_count == search_query_list.length) {
Q.allSettled(promises)
.then(function(result) {
console.log("All Promises Settled);
});
}); // Close foreach loop
在运行update_search_query_after_search方法后,推文表中的推文数量与search_query表中的推文数量不匹配。
答案 0 :(得分:1)
您的代码可以简化为
var promises = search_queries.map(function(val, index, array) {
return search_twitter(Q, val).then(function(tweets) {
return add_tweets(Q, tweets, val);
}).then(function(search_query) {
return update_search_query_after_search(search_query);
}).then(function(v) {
console.log("Chain is completed");
});
});
Q.allSettled(promises).then(function(result) {
console.log("All Promises Settled");
});
看看它是否适合你
答案 1 :(得分:1)
您可以通过映射源数组中的promise来以更简单(并且更不容易出错)的方式声明这一点:
//no need to state extra function params if you're not using them
var promises = search_queries.map(function(val){
return search_twitter(Q, val)
.then(function(tweets) {
// Add Tweets to tweets table
return (add_tweets(Q, tweets, val));
})
// Update number of tweets in search_queries table
.then(function(search_query){
// Update counts for search_search query and store it
return update_search_query_after_search(search_query);
})
.then(function(v){
console.log("Chain is completed");
}); // Close promise chain
});
Q.allSettled(promises)
.then(function(result) {
console.log("All Promises Settled);
});