简体   繁体   中英

Azure Cosmos db and functions javascript sdk - how to read document async?

I have the following code in an apollo resolver:

Mutation: {
    addChannel: (root, args) => {
      client.readDocument("website", {}, (x) => {
        return { id: "Test", name: "Test Channel " + args.name }
      });
    },

where client is a document client:

var DocumentClient = require('documentdb').DocumentClient;

When it's called I'd like to wait on client.readDocument to finish and give me a return value that I will return (the example above is super simple and won't do that)

The problem I have is readDocument does something asynchronously in the background but the function isn'ta sync so I can't await it, so the function immediately falls through before the callback has a chance to finish. After the return data is sent (which is undefined) the callback function (x)=>{...} occurs..

Three solutions I can think of here (which to use will depend on your exact situation):

  1. v2 of the Cosmos DB API has async/await support so you can use that instead of the callback.
  2. Wrap the callback code in a promise and await the promise.
  3. Use a non-async Azure Function and return the result with context.done(result) at the end of the callback.

I would suggest you move towards the v2 version of the Javascript API: https://github.com/Azure/azure-cosmos-js

That way you can use the fluent path to the items and use const { body: readDoc } = await item.read(); to read an item async.

You can find multiple samples on how this is done here

The nature of your code doesn't fit with the callback model that readDocument follows therefore you have no mechanism to pass the document back out from addChannel .

Presuming you don't need to do any pre-processing to the document beforehand, you could use a combination of promises and the async / await syntax eg

addChannel: (root, arg) => 
  new Promise((resolve, reject) => 
    client.readDocument("website", {}, (err, x) => 
      err ? reject(err) : resolve(x)
    )
  );
}

Then to "wait" on the document before executing other code

const doc = await obj.addChannel(...);
// use doc

Note - await can only be used within a function marked as async

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM