سؤال

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.

هل كانت مفيدة؟

المحلول

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
  }
};
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top