0

I am writing a helper class in JS for my web site that goes to the server and pulls back a fresh guid. I made this a helper function because I plan to use this functionality often on my site. The complication I am having is in writing a method that will return the string as a synchronous operation rather than return the promise as an asynch.

Here is the code I have so far:

//create a namespace for our helpers, just in case
var littleMouse = littleMouse || {};

//Class definition
littleMouse.Helper = function () { };

//method to request a new GUID from the server
littleMouse.Helper.prototype.newGuid = function () {
    return $.get("/api/Helper/Guid")
        .done(function (response) {
            console.log(response);
            return response;
    });
};

I want to be able to use code like this:

var myHelper = new littleMouse.Helper();
var myGuid = myHelper.newGuid();
alert(myGuid);

When I do this, myGuid is an object and not a string. And I have confirmed that -- of course -- my alert method is triggered before the console has logged the string, so the object being returned is probably the request / promise.

How do I update my code so that the newGuid() method is invoked synchronously and returns back the actual string?

Peter Lange
  • 2,786
  • 2
  • 26
  • 40
  • 1
    You should give up on trying to get the result synchronously. It is like ordering a pizza online, pressing the Order button, looking at your plate, and being surprised it is still empty. Embrace the asynchronous pattern. See referenced Q&A for lots of ideas and explanations. My advice is to use the `fetch` API, and `await` syntax. – trincot Jun 11 '20 at 19:38
  • "*goes to the server and pulls back a fresh guid*" - uh, the idea behind [GUIDs](https://en.wikipedia.org/wiki/Globally_unique_identifier) is that you *don't* have to fetch from a central server but can generate them on your own anywhere. – Bergi Jun 11 '20 at 21:13
  • @Bergi I am not aware of a JS implementation that doesn't acknowledge the possibility of collision due to the inconsistent implementation of the random numbers in browsers. Admittedly, I haven't looked for a new implementation lately, but since a mistake on this web app can costs the clients 1000s of dollars, I need to be very cautious.That said if you know of an implementation that can guarantee the uniqueness as well as the server can I would certainly be interested in that as an alternative. – Peter Lange Jun 11 '20 at 21:41
  • @PeterLange Looks like [there are solutions](https://stackoverflow.com/q/105034/1048572) that use the browser's crypto API for strong random numbers. And of course you might want to validate their uniqueness on the server anyway, if you don't trust the client and the stakes are that high. – Bergi Jun 11 '20 at 21:45
  • Thanks @Bergi I will look into that link you posted – Peter Lange Jun 11 '20 at 21:56

0 Answers0