等候執行結果才回傳
當你需要回傳各func的執行結果
模組化後,執行的實作在提整的func中,不做額外處理(等候)會直接被當成異步,造成先傳出response沒有取得真正的執行結果。
azure的基本範例就是用asyns掛在func前,讓回傳自動成為異步!
與asyns搭配使用的是「await」,強迫等候處理取得結果。
module.exports = async function (context, req) {
let responseMessage = "success";
let status = 200;
const action = context.bindingData.action;
await (function() {
if(action == "action"){
responseMessage = "處理了!";
}
else if(action == "ERR"){
responseMessage = "錯誤訊息";
status = 400;
}
})();
context.res = {
// status: 200, /* Defaults to 200 */
status: status,
body: responseMessage
};
}
await後基本上是接著function,這裡用匿名函式方式處理。
也可以直接放棄外層的異步。
但需要在最後呼叫「context.done();」以通知伺服器執行回傳。
然後用Promise的方法,將response的處理及context.done的呼叫當作callback傳入,在then裡執行伺服器回傳。
function search(q){
return new Promise(function(resolve, reject) {
...
});
}
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request!');
const q = (req.query.q || (req.body && req.body.q));
let doResponse = function(respMsg){
context.res = {
// status: 200, /* Defaults to 200 */
body: respMsg
};
context.done();
}
q ? search(q).then(doResponse) : doResponse("缺漏查詢條件!請輸入參數q值...");
}
這樣只會取得「success」(最一開始給定的值,並非執行處理後的值)。
module.exports = async function (context, req) {
let responseMessage = "success";
const action = context.bindingData.action;
if(action == "action"){
responseMessage = "處理了!";
}
else if(action == "ERR"){
responseMessage = "錯誤訊息";
}
context.res = {
body: responseMessage
};
}
如果await的function中還有需要等待的function,外面的function也必須為async,且await目標function,否則會無效。(如下範例)
var search = require(`./search`);
module.exports = async function (context, req) {
let responseMessage = "success";
let status = 200;
const action = context.bindingData.action;
if(action == "search"){
responseMessage = await search.search(req); //等候目標function
}
else if(action == "ERR"){
responseMessage = "錯誤訊息";
status = 400;
}
context.res = {
// status: 200, /* Defaults to 200 */
status: status,
body: responseMessage
};
}
var search = require(`./search`);
module.exports = async function (context, req) {
let responseMessage = "success";
let status = 200;
const action = context.bindingData.action;
await (function() { //等候目標為這個匿名func,內部的search卻沒等到
if(action == "action"){
responseMessage = search.search(req); //await得匿名func中無法直接再await
}
else if(action == "ERR"){
responseMessage = "錯誤訊息";
status = 400;
}
})();
context.res = {
// status: 200, /* Defaults to 200 */
status: status,
body: responseMessage
};
}
async function search(req){
let data = {};
await axios.get(url)
.then(function (response) {
// console.log(response);
// console.log(response.data);
data = response.data;
})
.catch(function (error) {
// console.log(error);
})
.then(function () {
// always executed
});
return data;
}
exports.search = search();
Last updated
Was this helpful?