0

When calling a JSON-RPC service what is the most common way to generate a unique ID from a JavaScript client?

REVISED QUESTION:

Typically, a JavaScript JSON-RPC client implements a counting id parameter (e.g. If the last request was id=1, and it hasn't received a response back, the next request is id=2. If the request with id=1 has responded, the next request can be id=1 again). I'm interested in understanding how people typically implement this.

Community
  • 1
  • 1
orokusaki
  • 55,146
  • 59
  • 179
  • 257

1 Answers1

1

You don't describe the universe in which this needs to be unique.

If you mean absolutely unique, then you're talking about a UUID.

If you need something unique to the endpoint to prevent client-side caching, then this will suffice

var unique = new Date().getTime();

If you need something other than these two then you'll need to be more specific.

EDIT

Maybe something that looks a bit like this

jsonRpcClient = function()
{
  var requestStack = [null];

  this.makeRequest = function()
  {
    var id = this.getAvailableSlot();
    requestStack[id] = new this.request( id, arguments );
  }

  this.getAvailableSlot: function ()
  {
    for ( var i = 0; i < requestStack.length: i++ )
    {
      if ( null == this.requestStack[i] )
      {
        return i;
      }
    }
    return i;
  }

  this.request: function( id, args )
  {
    // request stuff here
    // pass id and whatever else to jsonRpcClient.handleResponse()
  }

  this.handleResponse: function( id )
  {
    var request = requestStack[id];
    requestStack[id] = null;

    // Do whatever with request
  }
};
Community
  • 1
  • 1
Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • This is just for the client (browser) to match up requests with responses (for async requests). It's not that it has to be as unique as a UUID or even the current time. In fact it could almost always be `1`. It typically starts with `1`, then `2` and so-on, unless `1` is returned before another request is sent (ie, not async). In that case the id is always `1`. I'm more or less interested in finding out how most people are implementing this. I'm sorry for the poorly worded question. – orokusaki Dec 08 '10 at 20:09
  • Sounds like all you need is a "next-available-slot" type of stack, where the array element's index is going to be your ID. – Peter Bailey Dec 08 '10 at 21:17