【问题标题】:How can i set a timeout on google cloud datastore .get?如何在谷歌云数据存储 .get 上设置超时?
【发布时间】:2019-03-04 13:43:35
【问题描述】:

我刚开始使用一些谷歌云服务,我正在尝试从数据存储中获取一个实体。

如果客户端有互联网连接,一切顺利。

但我想为客户端因任何原因(如互联网)而无法访问数据存储区的情况添加一个 try catch 语句。

这是我的代码:

try{
    let search = datastore.key(['Client', Client_id])           
    datastore.get(search, /*{timeout: 1000},*/ function (err, entity) {
        console.log('limit >>>', entity.limit)
        evt.emit('comparedate', res, entity.limit)    
    });
}
catch(error){
    console.log('Error >>>', error)
}

我的问题是:连接尝试没有时间限制。当客户端无法访问互联网时,请求将永远“挂起”,并且不要进入捕获条件。

我尝试了一些参数,例如:Global#CallOptions,但没有成功。

感谢您的帮助!

编辑 >>>> 我知道这不是最值得信赖的方式。但现在我用这段代码解决了:

evt.on('isonline', (res) => {
    try{
        require('dns').lookup('google.com',function(err) {
            if (err && err.code == "ENOTFOUND") {
                console.log('NO INTERNET')
                evt.emit('readofflinedata', res)
            } else {
                console.log('WITH INTERNET')
                evt.emit('readonlinedata', res)
            }
        })
    }
    catch(error){
        res.status(200).send({ error: true, message: error.message })
    }   
})

【问题讨论】:

    标签: node.js google-cloud-platform google-cloud-datastore try-catch


    【解决方案1】:

    Datastore 客户端使用内部称为 google-gax 的库。您可以配置超时/等。通过传入gax options

    datastore.get(key, {
      gaxOptions: {timeout: 1000}
    }, (err, entity) => {
      // ...
    });
    

    【讨论】:

      【解决方案2】:

      我没有在datastore的get函数中找到任何参数来添加超时。但是,您可以使用 Promise 并设置一个计时器,如果函数执行时间过长,它将停止它。

      var Promise = require("bluebird");
      var elt = new Promise((resolve, reject) => {
         fun(param, (err) => {
           if (err) reject(err);
           doSomething(); // <- datastore.get() funtion
           resolve();
      });
      
      elt.timeout(1000).then(() => console.log('done'))
                       .catch(Promise.TimeoutError, (e) => console.log("timed out"))
      

      【讨论】:

      • 亚历克斯。我以前从未使用过承诺。我尝试了类似的方法: let cloudDatasrore = new Promise((resolve, reject)=>{ ... datastore.get(search, function (err, entity){ console.log('Data limite >>>>>>> >', entity.limit) }) }) evt.on('readonlinedata', (res) => { cloudDatasrore.timeout(5000).then(()=> console.log('>>>>>>> >>> WORK') ) .catch(Promise.TimeoutError, (e)=> console.log('>>>>>>>>>> NOT WORK', e) ) 在这种情况下,我会收到“NOT” WORK”消息,并且浏览器网络上的请求保持“pending”状态。我做错了什么?
      猜你喜欢
      • 2015-05-09
      • 1970-01-01
      • 2017-08-23
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      相关资源
      最近更新 更多