我正在使用Cloud Functions for Firebase在服务器端执行地理编码代码。在下面的代码中,sortDistance
只是我用来执行地理编码的端点。变量snapadd
在其中应包含地址时显示为空 - 我已经验证console.log(snapadd + " snap user address (((((((())))))))");
每次循环snap
时都会输出一个地址。它循环遍历所有地址,然后它尝试进行查询,所以我想知道我是如何使用Promise
的问题...也许地址不在那里当它需要是因为它在执行地理编码请求之前循环遍历所有这些 - 所以当地理编码请求发生时,地址是空的?我不确定。
var googleMapsClient = require('@google/maps').createClient({
key: 'xxx',
Promise: Promise
});
...
exports.sortDistance = functions.https.onRequest((req, res) => {
// Grab the text parameter.
const original = req.query.text;
console.log(req.query.text + " request body .......");
// Push the new message into the Realtime Database using the Firebase Admin SDK.
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("profiles/stylists");
var promises = [];
// Attach an asynchronous callback to read the data at our posts reference
ref.on("value", function(snapshot) {
//console.log(snapshot.val());
var snap = snapshot.val();
for(const user in snap) {
//promises.push(new Promise(function(resolve, reject) {
var snapadd = snap[user].address;
console.log(snapadd + " snap user address (((((((())))))))");
if(snapadd != null || typeof snapadd != undefined) {
googleMapsClient.geocode({
address: snapadd
}).asPromise()
.then(response => console.log(response.json.results));
.catch(err => console.log(err))
}
//}))
//console.log(typeof user + 'type of');
}
//var p = Promise.all(promises);
//console.log(p + " promises logged");
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
我从firebase functions
log:
{ error_message: 'Invalid request. Missing the \'address\', \'bounds\', \'components\', \'latlng\' or \'place_id\' parameter.',
results: [],
status: 'INVALID_REQUEST' },
requestUrl: 'https://maps.googleapis.com/maps/api/geocode/json?address=&key=AIzaSyBzXEp6HR01Pau5cotJ2wve1Z7aKEfvkUI',
query: { address: '', key: 'xxx' } }
显然,地址在不应该显示为空时显示为空。再次,查看日志的顺序,看起来所有地址在单个地理编码请求发生之前循环。感谢。