【问题标题】:typescript promise Rest Api打字稿承诺 Rest Api
【发布时间】:2020-03-10 00:16:27
【问题描述】:

我有以下代码,其中 registerCustomer 函数将调用 registerCustomerApi 从 Rest Api 获取数据。我想添加承诺,以便在返回前端之前等待休息 api 返回响应。请问如何添加promise?

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);
  }
}

【问题讨论】:

标签: typescript promise


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    相关资源
    最近更新 更多