Home > Software design >  Using async await on .then function with parameters
Using async await on .then function with parameters

Time:11-09

I'm doing some functional testing with mocha. I stored my functions name, parameters and sucess message in local JSON file. I am checking my database response with local JSON response. I'm using .then and .catch everywhere. I am looking to clean up a code with async await. How I can use async await here?

it('Check Authentication', (done) => {
    readFileData('checkAuth').then(({ params, message}) => {
      login.checkAuth({ ...params })
        .then((result) => {
          assert(result.message === message);
          done();
        })
        .catch((err) => done(err));
    });
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Something like this. Haven't tested it tho. Basically instead of .then() you just await the call. Note that there is async before (done) callback. .catch() can be caught with try/catch block.

it('Check Authentication', async (done) => {
       let response = await readFileData('checkAuth');
       try {
         let message = await login.checkAuth({ ...response.params }); // or w/e the response is
         // assert the message
       } (catch e) {
          // do something with the error
       }
    });

CodePudding user response:

  • Changed callback function to async to use `await
  • Wrapped all await calls in try-catch block to handle errors
  • Used const for params, message and result variables but if you are going to reassign values later in the code you can use let instead.
  • done() will be async call. Add await in front of that if you need that too to be sync call

it('Check Authentication', async (done) => {
    try {
        const { params, message } = await readFileData('checkAuth');
        const result = await login.checkAuth({ ...params });
        assert(result.message === message);
        done();
    } catch (err) {
        done(err);
    }
});
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related