I'm migrating an app from Azure Functions v1 to v2. The old app uses callbacks, and I prefer to stick to it so I won't mess up the app logic. I need to get data as array, and then within the callback, perform the app logic. However, while using callbacks in Cosmosdb sdk v2.1.1 I get error UnhandledPromiseRejectionWarning: Error: toArray takes no arguments
. Cosmosdb documentation doesn't have example of using callbacks in Node.js. Following is my code, could you please tell what's wrong in my code?
const CosmosClient = require('@azure/cosmos').CosmosClient;;
let config = {}
const endpoint = process.env.HOST;
const masterKey = process.env.COSMOS_DB_PRIMARY_KEY;
config.db_account = process.env.COSMOS_DB_ACCOUNT;
config.containerId = "games";
config.gameCollectionPath = "dbs/" + config.db_account + "/colls/games";
const client = new CosmosClient({
endpoint: endpoint,
auth: {
masterKey: masterKey
}
});
module.exports = function (context, req, game) {
client.database(config.db_account).container(config.containerId).items.query(querySpec).toArray(function (err, results) {
if (err) {
context.res = {}
context.done();
return;
}
if (my_condition_is_met) {
context.res = {}
context.done();
}
}
}
The v2 SDK does not support callbacks directly. You have to pass it along to the promise. Your error case and success case is also split with promises.
client.database("foo").container("bar").items.query(spec).toArray()
.then((response) => {
console.log(response.result)
})
.catch((err) => {
console.error("something went wrong with query", err);
});
FWIW, we definitely recommend async/await pattern. It makes the code a lot more compact and readable, but Promises with callbacks are totally fine too.