javascriptreactjsasynchronousmobxsuperagent

How do I use aysnc/await in this superagent call?


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

Solution

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