1
我在寫一個Azure函數,它使用npm模塊請求調用Google API。處理body
需要調用context.done()
或其他context.res
超出範圍(如果我在回調中設置它,然後等待在我的腳本末尾通過context.done()
)使用它的回調。如何在使用request()和回調函數時不在Azure函數中調用context.done()兩次?
的問題是我不理解如何既處理錯誤,並返回給客戶端和使用回調的響應。
對我的代碼的任何和所有意見都是值得歡迎的。我想改善。
var request = require('request');
module.exports = function (context, req) {
if (req.body) {
incoming = req.body
if (incoming.components && incoming.components.city
&& incoming.components.state
&& incoming.components.country) {
// locality = city
// administrative_area = state
var country = incoming.components.country;
var administrative_area = incoming.components.state;
var locality = incoming.components.city;
request.get({
url: "https://maps.googleapis.com/maps/api/geocode/json?components=country:US|locality:city|administrative_area:CA&key=..."
}, function (error, response, body) {
if (error) {
context.log(error);
}
if (!error && response.statusCode == 200) {
context.log(body)
}
context.res = {
status: 200,
body: "asdf"
};
context.done();
});
context.log("here");
} else {
context.res = {
status: 400,
body: 'There was data but not the right kind. Try {"components": {"country": "US","city": "city","state": "CA"}'
};
}
}
else {
context.res = {
status: 400,
body: 'Nothing was received. Try {"components": {"country": "US","city": "city","state": "CA"}'
};
}
context.done();
};
謝謝。這非常合理。 – Chris76786777
是嗎?因爲以這種方式生成錯誤不會在任何監視工具中顯示爲錯誤。似乎沒有辦法既產生錯誤又向用戶返回自定義響應。天青的一擊。 –