Сбой Azure Chatbot с «SyntaxError: Неожиданный идентификатор - cosmosClient.databases.createIfNotExists» при подключении к CosmosDB - PullRequest
0 голосов
/ 10 января 2019

Я чрезвычайно новичок в Azure Bot Services и платформе Azure в целом. Я пытаюсь создать Chatbot, используя node.js, но получаю сообщение об ошибке ниже при попытке подключиться к CosmosDB.

Бот работал нормально, прежде чем я добавил приведенный ниже код для подключения к CosmosDB.

Любая помощь или руководство по этому вопросу будет признателен!

P.S. - Я добавил пакет '@ azure / cosmos', и код запускается без ошибок, если я просто удаляю сегмент try-catch.

Код для подключения к CosmosDB:

var async=require("async"); 
var await=require("await"); 

const CosmosClientInterface = require("@azure/cosmos").CosmosClient;
const databaseId = "ToDoList"; 
const containerId = "custInfo"; 

const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";

const cosmosClient = new CosmosClientInterface({
    endpoint: endpoint,
    auth: {
      masterKey: authKey
    },
    consistencyLevel: "Session"
  });

async function readDatabase() {
   const { body: databaseDefinition } = await cosmosClient.database(databaseId).read();
   console.log(`Reading database:\n${databaseDefinition.id}\n`);
}

Сообщение об ошибке:

Sat Jan 12 2019 03:40:08 GMT+0000 (Coordinated Universal Time): Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
      ^^^^^^^^
SyntaxError: Unexpected token function
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
    at Module._compile (module.js:570:32)
Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
      ^^^^^^^^
SyntaxError: Unexpected token function
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
    at Module._compile (module.js:570:32)

1 Ответ

0 голосов
/ 10 января 2019

Вы не можете ждать, не находясь в функции async.

Скопируйте весь ваш код в метод async function main(){}, затем вызовите main().catch((err) => console.log(err)); или что-то подобное, чтобы запустить обещание и обработать ошибки.

Вы можете увидеть образец такого типа рисунка здесь в этом примере: https://github.com/Azure/azure-cosmos-js/blob/master/samples/ChangeFeed/app.js#L33

--- РЕДАКТИРОВАТЬ 1 ---

Вот ваш пример, переписанный с Обещаниями:

const CosmosClientInterface = require("@azure/cosmos").CosmosClient;
const databaseId = "ToDoList"; 
const containerId = "custInfo"; 

const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";

const cosmosClient = new CosmosClientInterface({
    endpoint: endpoint,
    auth: {
      masterKey: authKey
    },
    consistencyLevel: "Session"
  });

cosmosClient.database(databaseId).read().then(({body: databaseDefinition}) => {
   console.log(`Reading database:\n${databaseDefinition.id}\n`);
}).catch((err) {
   console.err("Something went wrong" + err);
});

В приведенном выше примере вам не нужно импортировать async / await, теперь это ключевые слова в JavaScript.

Вот запись в блоге, которая сравнивает и сравнивает Async / Await и Promises: https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789

...