About asynchronous methods

About asynchronous methods

All Couchbase SDKs provide data operations as synchronous methods. In the case of synchronous methods, your application will block and not continue executing until it receives a response from Couchbase Server. In most SDKs, notably Java, Ruby and PHP, there are data operations you can perform asynchronously; in this case your application can continue performing other, background operations until Couchbase Server responds. Asynchronous operations are particularly useful when your application accesses persisted data, or when you are performing bulk data stores and updates.

There are a few standard approaches in Couchbase SDKs for asynchronous operations: 1) performing the asynchronous method, then later explicitly retrieving any results returned by Couchbase server that are stored in run-time memory, 2) performing an asynchronous method and retrieving the results from memory in a callback, and/or 3) perform an event loop which waits for and dispatches events in the program.

The following briefly demonstrates the first approach, where we perform an asynchronous call and then later explicitly retrieve it from run-time memory with a second call. The sample is from the PHP SDK:

<?php $cb = new Couchbase(); $cb->set('int', 99); $cb->set('array', array(11, 12)); $cb->getDelayed(array('int', 'array'), true); //do something else var_dump($cb->fetchAll()); ?> 

In the first two lines we create a new Couchbase client instance which is connected to the default bucket. Then we set some sample variables named int and array . We perform an asynchronous request to retrieve the two keys. Using the fetchAll call we can retrieve any results returned by Couchbase server which are now in run-time memory.

This is only one example of the pattern of method calls used to perform an asynchronous operation. A few more examples will follow in this section, therefore we introduce the concept here. For more information, see Synchronous and asynchronous transactions .