Search code examples
node.jsaerospike

Aerospike synchronous get method for node.js client


Is there any synchronous database read and write method in Aerospike for Node.js client?


Solution

  • All the API calls in the Aerospike client client use an async. pattern to connect, read data etc, this is to be expected in Node.js.

    You can use the new (since Node 7.6) async/await keywords to allow code to be written in a more readable way though. It is not synchronous (since testRead does not block) but it reads much more like synchronous code.

    const Aerospike = require('aerospike')
    var batchRecords = [
      { key: new Aerospike.Key('test', 'demo', 'key1'), bins: ['i', 's'] },
      { key: new Aerospike.Key('test', 'demo', 'key2'), read_all_bins: true },
      { key: new Aerospike.Key('test', 'demo', 'key3') }
    ];
    
    async function testRead()
    {
        var result = await readFromAerospike(batchRecords);
        console.log(result);
    }
    
    function readFromAerospike(batchRecords) {
       return new Promise((resolve, reject) => {
           Aerospike.connect((err, client) => {
              if (err) {
                  reject(err);
              } else {
                  client.batchRead(batchRecords, (err, results) => {
                      if (err) {
                          reject(err);
                      } else {
                          resolve(results);
                      }
                  })
              }
           });
       });
    }
    
    testRead();