2017-06-23 48 views
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(); 
}; 

回答

2

您不應該在函數結束時調用context.done()。只有當你有結果時(即當你檢測到錯誤或在回調中)時才調用它。有一些重構和簡化版本的功能:

module.exports = function (context, req) { 
    if (!req.body) { 
     context.res = { 
      status: 400, 
      body: 'Nothing was received. Try {"country": "US"}' 
     }; 
     context.done(); 
     return; 
    } 

    if (!req.body.country) { 
     context.res = { 
      status: 400, 
      body: 'There was data but not the right kind. Try {"country": "US"}' 
     }; 
     context.done(); 
     return; 
    }   

    request.get({ 
     url: "https://www.google.com?q=" + req.body.country 
    }, function (error, response, body) { 
     if (error) { 
      context.log(error); 
      context.res = { 
       status: 500, 
       body: "Unexpected error" 
      }; 
     } else { 
      if (response.statusCode == 200) { 
       context.log(body) 
      } 
      context.res = { 
       status: 200, 
       body: "asdf" 
      }; 
     } 
     context.done(); 
    }); 
}; 
+0

謝謝。這非常合理。 – Chris76786777

+0

是嗎?因爲以這種方式生成錯誤不會在任何監視工具中顯示爲錯誤。似乎沒有辦法既產生錯誤又向用戶返回自定義響應。天青的一擊。 –