从For循环中获取promise的结果的最佳方法是什么? 在此示例中,代码在循环结束时resultArray未完成。
var resultArr = [];
var itemArray1 = [1, 2, 3, 4, 5];
var itemArray2 = ['a','b','c','d','e'];
for (var a = 0; a < itemArray1.length; a++) {
for (var b = 0; b < itemArray2.length; b++) {
myPromise(a,b)
.then(function(result) {
if (result != null) {
resultArr.push(result);
}
});
}
}
// resultArray is still not complete
function myPromise(a,b) {
return new Promise(function(resolve, reject) {
// request to mongodb
myTable.findOne({ _id:a, name:b }, function(err,result) {
if (err) throw err;
resolve(result);
});
});
}
答案 0 :(得分:1)
您可以使用def check_if_works():
import operator
dict_info = {}
dict_info['math 12345'] = 10
dict_info['math 1234'] = 2
dict_info['math 123'] = 1
dict_info['SCI 124'] = 16
dict_info['SCI 345'] = 2
result={}
keys = {}
for key, value in dict_info.iteritems():
try:
if result[key.split()[0]] < value:
result[key.split()[0]] = value
keys[key.split()[0]] = key
except KeyError:
result[key.split()[0]] = value
keys[key.split()[0]] = key
#replace the key prefixes with full length key
for key in keys.keys():
result[keys[key]] = result.pop(key)
return result
dict_info = check_if_works()
print dict_info
和forEach
Promise.all
答案 1 :(得分:1)
在我看来,做到这一点的最简洁方法是将Promise.all()
与Array#map
一起使用。另外,请确保让您的功能保持干净简洁,并为其提供有意义的名称!
var itemArray1 = [1, 2, 3, 4, 5];
var itemArray2 = ['a','b','c','d','e'];
function flatten(arrays) {
return [].concat(arrays);
}
function queryAs() {
return Promise.all(itemArray1.map(queryBs))
// the result is an array of arrays, so we'll flatten them here
.then(flatten);
}
function queryBs(a) {
return Promise.all(itemArray2.map(function (b) {
return performQuery(a, b);
}));
}
// resultArray is still not complete
function performQuery(a, b) {
return new Promise(function(resolve, reject) {
// request to mongodb
myTable.findOne({ _id:a, name:b }, function(err,result) {
if (err) throw err;
resolve(result);
});
});
}
queryAs().then(function (results) {
console.log(results);
});