我需要幫助我正在創建一個節點天氣應用程序。我使用Google API來獲取地址的經緯度,並將其反饋到Dark Sky API中,以便以JSON格式返回天氣。Api數據與異步的Node.js和檢索數據使其同步
我的問題是,在谷歌API返回經度和緯度之前,大部分時間天氣API執行搜索。我知道爲什麼它會這樣做,因爲Node的異步特性。我的問題是如何讓這部分同步?
var express = require('express');
var https = require('https')
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var lon;
var lat;
app.post('/', function(req,res,next){
var search = req.body.search;
function google(){
var api = "API-KEY";
var url = https.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${search}&key=${api}`, function(res3){
var body = "";
var googleResults;
res3.on('data', function(data){
body += data.toString();
})
res3.on('end', function(){
googleResults = JSON.parse(body);
//console.log(body);
lat = googleResults.results[0].geometry.location.lat;
lon = googleResults.results[0].geometry.location.lon;
console.log(search);
})
});
}
google();
//connectc to API URL()
var request = https.get(`https://api.darksky.net/forecast/API-KEY/${lon},${lat}`, function(res2){
console.log(lon + " " + lat)
var body = "";
var weather;
//Read the data
res2.on('data', function(data){
body += data.toString();
})
res2.on('end', function(){
//Parse the data
weather = JSON.parse(body);
//Print data
//console.log("test = " + weather.currently.temperature)
res.render('index', {
temperature: weather.currently.temperature,
humidity: weather.currently.humidity,
wind: weather.currently.windSpeed
});
})
});
});
你不能讓它同步!一種選擇是隻有在google結果完成後才調用天氣api –
您在本文中發佈了您的API密鑰,它在編輯中被刪除,但仍然公開曝光。你應該撤消它並重新發佈一個新密鑰。 – Adam
@亞當謝謝我已經有了,應該在發佈之前加倍檢查。 – monkeyman905