chuckd
chuckd

Reputation: 14530

How to make my javascript function async when it's scoped

I have a method called 'updateStatus' in one of my js files. I'm scoping everything in each JS file like below.

Now I want to make this function asynchronous, but if I put a async in front of the function declaration like below I get an error saying it expects a semi colon on that same line.

scope.updateStatus = async function(profileId, isConnected)

'use strict';

// Set local tp namespace
if (typeof yb === 'undefined')
  var yb = {};

$(function() {
  yb.chat.initializeChat();
});

yb.chat = new function() {
  var scope = this;

  scope.initializeChat = function() {
    scope.initializeHub();
  };

  scope.updateStatus = function(profileId, isConnected) {
    // do some work
  };

  scope.initializeHub = function() {
    scope.chat = $.connection.chatHub;

    scope.chat.client.setConnectionStatus = function(profileId, isConnected) {
      scope.updateStatus(profileId, isConnected);
    };
  };

};

Upvotes: 0

Views: 817

Answers (1)

Alex Lawrence
Alex Lawrence

Reputation: 36

tldr: Overall, the answer to your question is to do one of the following three things:

  1. Use browsers that support async
  2. Use Promises and use browsers that support Promises
  3. Do not use async (or Promises).

It would help to explain where you get that error. I'm assuming it's when executing the code in your browser. Further, I'm assuming your browser simply does not support the async keyword.

Have a look at the following code:

const scope = {};

scope.foobar = async function() {
  return new Promise(resolve => {
    console.log('foobar');
    resolve();
  });
};

scope.foobar();

If you execute this code (e.g. via https://jsbin.com) in a recent Firefox or Chrome browser, it works. However, in an other/older browser it might cause the error you are describing.

If my assumption is wrong, please further clarify.

Upvotes: 2

Related Questions