首页 > 解决方案 > 打字稿承诺 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);
  }
}

标签: typescriptpromise

解决方案


对于您想要的输出,您只需要在函数调用之前添加 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)
            }
        })
    })
}

推荐阅读