Chee Mun
Chee Mun

Reputation: 85

typescript promise Rest Api

I has the following codes which registerCustomer function will call registerCustomerApi to get data from Rest Api. I want to add in promise in order to wait for rest api return response before it return to front-end. May I know how can I add in 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);
  }
}

Upvotes: 0

Views: 2817

Answers (1)

Ankur Patel
Ankur Patel

Reputation: 488

For your desire output you only need to add await keyword before your function call like this

var result = await registerCustomerApi(request.body.CompanyId, request.body.DateOfBirth, request.body.MobileNo);

update your function

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

Upvotes: 1

Related Questions