0

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.

Abdul Manaf
  • 4,933
  • 8
  • 51
  • 95
  • 1
    You are awaiting something that *isn't returning a promise*; request has a callback API. You need to use a promisified version of request (e.g. https://www.npmjs.com/package/request-promise-native) or create a `new Promise` and handle revolving and rejecting it yourself in the callback (see e.g. https://stackoverflow.com/q/22519784/3001761). – jonrsharpe May 13 '19 at 07:12

1 Answers1

1

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();
Paresh Barad
  • 1,544
  • 11
  • 18