简体   繁体   English

如何在使用Node.js时同步获取实体

[英]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! 我想同步获得结果!

You can write a helper function which returns Promise to make it synchronous (or simulate it) 您可以编写一个帮助程序函数,该函数返回Promise使其synchronous (或模拟)

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 然后,您可以在代码中的其他地方使用async/await (以暂停执行),例如

Note you can use await only inside async function 注意您只能在async函数中使用await

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) 或带有简单的承诺(请注意,这不会暂停执行,里面的代码then是回调函数)

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

Also looks like cosmos have now sdk with Promise support. 看起来cosmos现在已经有了Promise支持的sdk

Read more about Promise and async/await on MDN 阅读有关在MDN上的Promiseasync/await更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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