Asynchronous API
The Aerospike Node.js client supports Node.js-style callbacks as well as Promises for all asynchronous database operations. This tutorial demonstrates both methods of asynchronous client operations.
Example
This example demonstrates how to write a large set of records asynchronously. You can also use other database calls such as Batch
, Delete
and Scan
asynchronously.
const Aerospike = require('aerospike')const async = require('async')
const recordMax = 100000;const writeTimeout = 5000;let limit = 100;let inFlight = 0;
const records = Array.from({ length: recordMax }, (_, i) => i)
;(async function () { let client promises = [] try { client = await Aerospike.connect() results = [] await async.eachLimit( records, limit, async (i) => { const key = new Aerospike.Key('test', 'test', i) const bins = { name: 'Example', age: 31, id: i } results.push(await client.put(key, bins)) } ) console.log(results) console.log(results.length) } catch (error) { console.error('Error:', error) process.exit(1) } finally { if (client) client.close() }})()
This example is the same as the example above, but instead leverages callbacks instead of promises.
const Aerospike = require('aerospike')
function abort (error, client) { //console.error('Error:', error) if (client) client.close() process.exit(1)}
function put_callback(error, result){ count++; console.log(result) if (count >= recordMax) { if (globalClient) globalClient.close() console.log("Records written: " + count); return; }
if (count % 10000 == 0) { console.log("Records written: " + count); }}
let globalClient;const recordMax = 100000;const writeTimeout = 5000;let count = 0;
Aerospike.connect(function (error, client) { if (error) abort(error, client) globalClient = client; for (var i = 0; i < recordMax; i++) { let key = new Aerospike.Key('test', 'test', i)
let bins = { name: 'Example', age: 31, id: i } client.put(key, bins, put_callback)
}})