3

This is a superagent call, I have imported request(i.e is exported from my superagent component class) How do I use async/await in this for "res.resImpVariable".

request
  .post(my api call)
  .send(params) // an object of parameters that is to be sent to api 
  .end((err, res) => {
  if(!err) {
     let impVariable = res.resImpVariable;
  } else {
    console.log('error present');
   }
  });

1 Answers1

2

I reformulated my answer. I think I was misinterpreting before. You could wrap the entire sequence into a Promise-returning function that resolves after the response callback:

    function callSuperagent() {
        return new Promise((resolve, reject) => {
            return request
                .post(my api call)
                .send(params) // an object of parameters that is to be sent to api
                .end((err, res) => {
                    if(!err) {
                        console.log('get response', res);
                        // uncomment this to see the catch block work
                        // reject('Bonus error.');
                        resolve(res);
                    } else {
                        console.log('error present', err);
                        reject(err);
                    }
                });
        });
    }

Then, you can create an async function and await that:

    async function doSomething() {
        try {
            const res = await callSuperagent();

            // uncomment this to see the catch block work
            // throw 'Artificial error.';

            console.log('res', res);

            console.log('and our friend:', res.resImpVariable);
        } catch (error) {
            throw new Error(`Problem doing something: ${error}.`);
        }
    }

    doSomething();

Or if you don't make doSomething, it would be like this:

callSuperagent()
    .then((res) => {
        console.log('res', res);
        console.log('and our friend:', res.resImpVariable);
    })
    .catch((err) => {
        console.log('err', err);
    })
agm1984
  • 15,500
  • 6
  • 89
  • 113
  • thankyou, where do I add the doSomething method? immediately after resolve? –  Jun 04 '20 at 06:25
  • Everything is included inside there. You would replace everything you have now with two function definitions (which could be anywhere in that file) and just the one call to `doSomething()`. It's very hard for me to improve what I'm saying because I can't see what comes before and after `request.post().send().end()` – agm1984 Jun 04 '20 at 06:32