Making a function Async

I’m trying to use Async/Await but my code is throwing. I have this method here that calls out to an HTTP call and does some other processing on login. I don’t want the user to have to wait for this function to finish before they’re able to proceed – so I’d like to make it async. Am I doing this correctly?

// All server-side code:

import { Mongo } from 'meteor/mongo';
import { HTTP } from 'meteor/http';
import moment from 'moment';

const test = {};
async test.getExistingOrNewThing = userId => {
  let thing = null;
  if (await test.expiredOrNotExistsThing(userId)) {  // HTTP call inside here
    thing = await test.getNewThing(userId); // HTTP call inside here
    return thing;
  }
  else {
    thing = await test.getThing(userId);
    return thing;
  }
}


export { test };

Exception:

Unexpected token, expected => (115:12)

// package.json:

"babel-runtime": "^6.23.0"

Also, I’m on Meteor 1.5.

The async keyword needs to immediately precede the formula it applies to. So in your example you want it when you declare the arrow function

const test = {};
test.getExistingOrNewThing = async userId => {
//                           ^^^^^ keyword goes immediately before function statement
  let thing = null;
2 Likes

Thanks! Now this complies.

My new question is will this function now allow me to call it and move on to other things without holding other tasks?

// /imports/erver/test.js
import { Mongo } from 'meteor/mongo';
import { HTTP } from 'meteor/http';
import moment from 'moment';

const test = {};
test.getExistingOrNewThing = async userId => {
  let thing = null;
  if (await test.expiredOrNotExistsThing(userId)) {  // HTTP call inside here
    thing = await test.getNewThing(userId); // HTTP call inside here
    return thing;
  }
  else {
    thing = await test.getThing(userId);
    return thing;
  }
}


export { test };

I’m calling this function when the user logs on like this:

// server-side onLogin (NOT client)
import { test } from '../imports/server/test';

Accounts.onLogin(user => {
  const userId = user && user.user && user.user._id || '';
  test.getExistingOrNewThing(userId);
});

Will the above call to test.getExistingOrNewThing(userId); be called async, without holding up other events that get fired after Accounts.onLogin?

it will!

All async functions return a promise, so if you want to do something with the result, you’ll want to use .then() and .catch() methods on your function call

1 Like

Thanks @coagmano, for this case, I don’t actually need to do anything with it afterwards, I just don’t want the function to hold things up is all – so I guess in my case calling the async method like this will suffice:

// server-side onLogin (NOT client)
import { test } from '../imports/server/test';

Accounts.onLogin(user => {
  const userId = user && user.user && user.user._id || '';
  test.getExistingOrNewThing(userId);
});

Thanks

1 Like