I am trying to query Twin information from Azure IoT hub using sample code as below. But I not sure why we need query.nextAsTwin(onResults) 2 times. Any impact if I remove the 2sd one?
reference: https://github.com/Azure/azure-iot-sdk-node/blob/main/service/samples/javascript/twin_query.js
var Registry = require('azure-iothub').Registry;
var connectionString = process.env.IOTHUB_CONNECTION_STRING;
var registry = Registry.fromConnectionString(connectionString);
var query = registry.createQuery('SELECT * FROM devices', 100);
var onResults = function(err, results) {
if (err) {
console.error('Failed to fetch the results: ' err.message);
} else {
// Do something with the results
results.forEach(function(twin) {
console.log(twin.deviceId);
});
if (query.hasMoreResults) {
query.nextAsTwin(onResults);
}
}
};
query.nextAsTwin(onResults);
CodePudding user response:
As per IoT Hub query language for device and module twins, jobs, and message routing:
The query object is instantiated with a page size (up to 100). Then multiple pages are retrieved by calling the
nextAsTwin
method multiple times.
If you have more than 100 page size then you can call nextAsTwin
twice, otherwise you can remove the redundancy.
You can refer to other example: Get started with device twins (Node.js)
CodePudding user response:
In the code, you posted, onResults
is a function that prints out the device ID for every twin returned in the query result. If the query indicates more results, it calls query.nextAsTwin(onResults);
again. This is not redundant; it's a recursive function that will keep calling itself until there are no more results in the query.
In your example, the query will return 100 results at a time, as specified in the pageSize parameter in your code:
registry.createQuery('SELECT * FROM devices', 100);
So multiple calls to nextAsTwin
will be necessary when there are more than 100 results.