I have created a node.js application using promise. I have following code

async clientCall() {

    const baseUrl = 'https://localhost:44300/test';
    const queryString = '';
    var options = {
        uri: baseUrl + queryString,
    };
    process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
    var result =  await request.get(options, function (err: any, res: any, body: any) {
        console.log("Result: ", body)
        return body;
    })

     console.log("response:",result);
    // return result;
}

await ClientRepository.clientCall().then(data => {

    console.log("inside data: ",data)

    return data;
})

But i got output like this

response:
Result: My response
inside data: undefined
inside data: My response

I need to return response only after await request is completed.

1 Answers

1
Paresh Barad On Best Solutions

I think the following is your solution. If a Promise is passed to an await expression, it waits for the Promise to be fulfilled and returns the fulfilled value.

async function clientCall() {
    return new Promisse((resolve, reject) => {
        const baseUrl = 'https://localhost:44300/test';
        const queryString = '';
        var options = {
            uri: baseUrl + queryString,
        };
        process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
        request.get(options, function (err: any, res: any, body: any) {
            resolve(body);
        })
    });
}

async function callClientCall(){
    let clientCallResult = await ClientRepository.clientCall();
}

Simple example:

function resolveAfter2Seconds(x) { 
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function f1() {
  var x = await resolveAfter2Seconds(10);
  console.log(x); // 10
}
f1();