1 回答
TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
通過展平嵌套的 Promise,您可以看到您的代碼正在執(zhí)行以下指令(當(dāng)axios調(diào)用未引發(fā)錯(cuò)誤時(shí)):
admin.database().ref(`/venue-menus/${locationId}/`).set(response.data))
.then(response => res.status(200).send(locationId))
.catch(err => res.status(500).send({error: err})
.then(response => res.status(200).send(locationId)) // this line is always called after either of the above.
.catch(err => res.status(500).send({error: err})
作為一般做法,除非需要,否則不應(yīng)將 promise 與它們自己的then()和catch()處理程序嵌套,因?yàn)樗鼤?huì)導(dǎo)致像這樣的奇怪效果。
此外,如果您的代碼需要使用//end axios或//end cors消息,您應(yīng)該扁平化您的代碼,以便在沒有這些消息的情況下有意義。
將您的代碼調(diào)整為“快速失敗”,更正您的 API 響應(yīng)并適當(dāng)隱藏錯(cuò)誤堆棧跟蹤可以提供:
const cors = require('cors')({
origin: true,
methods: ["GET"]
});
exports.doshiiGetMenuForOnboardedVenue = functions.https.onRequest((req, res) => {
cors(req, res, (err) => { // note: cors will handle OPTIONS method
if (err) {
// note: log full error at ERROR message level
console.error('Internal CORS error:', err);
// note: return only generic status message to client
return res.status(500).json({error: 'Internal Server Error'});
}
// Forbidding anything but GET requests.
if (req.method !== 'GET') {
// 405 METHOD_NOT_ALLOWED
return res.status(405)
.set('Allow', 'GET')
.json({error: 'Not Allowed!'});
}
const locationId = req.query.locationId;
console.log('locationId', locationId);
if (!locationId) {
// 400 BAD_REQUEST
return res.status(400).json({error: 'locationId missing'})
}
var token = jwttoken();
const options = {
headers: {
'content-type': 'application/json',
'authorization': 'Bearer ' + token
}
};
// note: Don't forget to enable billing for third-party APIs!
const uri = 'https://sandbox.doshii.co/partner/v3/locations/' + locationId + '/menu?lastVersion=:lastVersion&filtered=true'
axios.get(uri, options)
.then(response => admin.database().ref(`/venue-menus/${locationId}/`).set(response.data))
.then(() => {
// note: as locationId was already sent by the client, send new/useful
// information back or nothing but the right status code
res.status(200).json({ ref: `/venue-menus/${locationId}/` });
})
.catch(err => {
// note: log full error at ERROR message level
console.error('Failed to retrieve/save API data:', err);
// note: return only message to client
res.status(500).json({error: err.message || 'Internal Server Error'});
});
});
});
添加回答
舉報(bào)
