Search code examples
node.jsazure-storage-account

How to get Entities synchronously while using Nodejs


I'm trying to get storage account's Table's data. I succeed in getting the date using the way here.

But it's using callback. I want to get the results synchronously!


Solution

  • You can write a helper function which returns Promise to make it synchronous (or simulate it)

    function getSome(mytable, hometasks, num)
      return new Promise((resolve, reject) => {
        tableSvc.retrieveEntity(mytable, hometasks, num, function(error, result, response){
          if(!error){
            resolve(entity // result or response etc)
          } else {
            reject(error)
          }
        });
      })
    

    Then you can use elsewhere in your code with async/await (to pause execution) like

    Note you can use await only inside async function

    async function useData() {
      const data = await getSome('mytable', 'hometasks', '1');
      // use data here
    }
    

    or with plain promise as (Note, this does not pause execution, code inside then is a callback function again)

    const data = getSome('mytable', 'hometasks', '1');
    data.then(res => // do something)
    

    Also looks like cosmos have now sdk with Promise support.

    Read more about Promise and async/await on MDN