typescript - 打字稿承诺 Rest Api
问题描述
我有以下代码,其中 registerCustomer 函数将调用 registerCustomerApi 以从 Rest Api 获取数据。我想添加承诺,以便在返回前端之前等待休息 api 返回响应。我可以知道如何添加承诺吗?
export const registerCustomer = functions.https.onRequest(async (request, response) => {
try {
//Consume api to validate whether is valid customer
var result = registerCustomerApi(request.body.CompanyId, request.body.DateOfBirth, request.body.MobileNo);
if (result != null) {
response.send(result);
}
else {
response.send(request.body);
}
}
catch (error) {
console.error(error);
}
})
function registerCustomerApi(companyId: String, dateOfBirth: String, mobileNo: String) {
try {
request.get(`http://localhost:57580/api/aes_brand/customer/validate_customer/SG01/1990-01-01/8299687`)
.then(function (response) {
return response;
})
.catch(function (err) {
console.error(err);
});
}
catch (error) {
console.error(error);
}
}
解决方案
对于您想要的输出,您只需要在函数调用之前添加 await 关键字,如下所示
var result = await registerCustomerApi(request.body.CompanyId, request.body.DateOfBirth, request.body.MobileNo);
更新你的功能
function registerCustomerApi(companyId: String, dateOfBirth: String, mobileNo: String) {
return new Promise((resolve, reject) => {
request.get(`http://localhost:57580/api/aes_brand/customer/validate_customer/SG01/1990-01-01/8299687`, function (error, response, body) {
if(error) {
reject(error);
} else {
resolve(body)
}
})
})
}
推荐阅读
- docker - 在 Gitlab CI 中使用 docker 图像时,我如何尊重服务的别名
- angular - 插件 Base64 不适用于 ionic 3
- angular - 无法读取角度 4 中未定义值的属性
- dns - 服务名称在主节点而不是其他节点上解析
- android - Google Play Console - 翻译服务:我可以在 xml 文件中描述我的字符串吗?
- python - 完成测试后,用分类模型预测重新填充数据框的替代方法?
- android - 对于 Android,我如何从 SQLite 中的日期和日期范围获取数据,其中 Android 变量可以传递给查询?
- java - 请放心接收 null 的实际值,但邮递员显示值存在
- google-chrome - VS2017 15.7.1版禁用F5调试new-Chrome-window
- d3.js - D3双击重置粘性节点