在Meteor中,我有一个完整的异步地理编码请求发送到google maps api。 完成所有地理编码后,我想显示一个包含所有失败的地理编码尝试的表。 什么是最好的模式?据我所知,我有三个选择:
承诺 - 我可以将google地图回调设置为承诺&使用thenable返回错误boolean,可能使用bluebird polyfill。
NPM异步 - 我可以在每次迭代时调用async.each
&如果它是最后一个,则返回错误boolean,如下所示:How to call a function after an asynchronous for loop of Object values finished executing
使用会话变量,如下所示:
Deps.autorun(function() {
console.log(Session.get('hasError'));
});
创建一个流星方法&使用Meteor.wrapasync
???
任何有关Meteor最佳实践的指导都会很棒,谢谢!
答案 0 :(得分:3)
我就是这样做的:
// Local collection, not synced to server
var geocodeErrors = new Mongo.Collection();
// Reactive variable to track completion
var geocodingComplete = new ReactiveVar(false);
var lookupThings = function (addresses) {
// How many are there?
var count = addresses.length;
// Count how many requests are complete
var complete = 0;
// Use underscore to make iteration easier
_.each(addresses, function (address) {
geocode(address, function (results, status) {
if (status === "OK") {
// do whatever
} else {
geocodeErrors.insert({
address: address,
otherData: "whatever"
});
}
complete++;
if (complete === count) {
geocodingComplete.set(true);
}
});
});
}
Template.results.helpers({
geocodeErrors: function () {
// Use an if statement to only display the errors when everything is done
if (geocodingComplete.get()) {
return geocodeErrors.find();
}
}
});
您可以使用此模板显示列表:
<template name="results">
<ul>
{{#each geocodeErrors}}
<li>Address failed: {{address}}</li>
{{/each}}
</ul>
</template>
我认为最重要的是Meteor风格是使用反应变量和集合而不是回调。
答案 1 :(得分:1)
直到另一个答案出现(请!),我通过向循环函数添加一个回调处理程序解决了这个问题,当我调用该循环时,我传入了我的回调函数。
lookupAddress(function(hasError, errArr) {
if (hasError === false) {
console.log("no errors");
} else {
console.log (errArr);
}
});
以下是从实际功能中删除的好部分......
function lookupAddress(callback) {
var hasError = false;
var errArr = [];
var cursorClosed = false;
var outstandingCalls = 0;
for (i = 0; i < n; i++) {
(function (j) { //wrap in an iffe to get 'i' byVal, not byRef
if (j === n - 1) cursorClosed = true; //check if I'm on the last iteration
geocoder.geocode({'address': address}, function (results, status) {
if (status === "OK") {
doSomethingFancy();
} else {
hasError = true;
errArr.push(arr[j]);
}
outstandingCalls--; //reduce queue for each completed async call
if (cursorClosed && outstandingCalls === 0) { //if no more iters and we're on the last async call
return callback(hasError, errArr)
}
});
})(i);
outstandingCalls++; //for each loop iter add 1 to the async queue
}
}