节点,承诺,返回值

时间:2018-01-15 01:47:39

标签: javascript node.js memcached blocking

我正在尝试编写一个位于memchached服务器之上的节点应用程序。目标是在几个站点之间共享一些数据,在memcache中缓存一些数据。

我在memcache中使用'get'找到的所有示例都返回一个promise,然后是console.log。但是,我需要返回给函数调用者的值。因此,我放宽了范围。

有任何一个例子可以作为阻止来电吗?

class TPCacheManager{
    constructor(){
        this.getVal = '';


    }
    setItem(type,key,item){
        var mcacheClient = new MemcachePlus();
        mcacheClient.set("TP:IDX","3");
    }

    getItem(key){
        var mcacheClient = new MemcachePlus();
        mcacheClient.get("TP:IDX").on((data, status, headers, config) => {
              console.log(data.data);
              this.getVal= data;    // <-- make this value available to the class
            });
    }

    theVal(){
        return this.getVal;
    }

}

2 个答案:

答案 0 :(得分:1)

您的问题基本上转化为:

  

将天空刮板跳入装满水箱的最佳方法是什么?   鲨鱼头上戴着激光。

答案基本上是:&#34;你没有&#34;

为什么ECMAScript使用回调和promises以及async await语法(基本上是使用不同语法的承诺),here解释了文档链接和非常好的视频。

假设您正在使用this memecached客户端,您可以将值成员设置为promise,代码有点令人困惑,因为您在调用setItem时没有设置值。 GetItem设置了值,但我认为如果你将它命名为lastRetreivedValue(并且可能根据你的需要添加lastSetItem)会更好:

class TPCacheManager{
  constructor(){
      this.lastRetrievedValue = Promise.reject("No item has been set");
  }
  setItem(type,key,item){
      var mcacheClient = new MemcachePlus();
      //the caller may want to know when it's finished and if it failed
      return mcacheClient.set("TP:IDX","3");
  }

  getItem(key){
      var mcacheClient = new MemcachePlus();
      const me = this;
      //caller may want to know when it's finished and if it failed
      return mcacheClient.get("TP:IDX").
      then(value => {
        console.log(value);
        me.lastRetrievedValue= value;
        //you may want to return value here so o.getItem().then(value
        //actually resolves to something other than undefinded
      });
  }

  theVal(){
      return this.lastRetrievedValue;
  }

}

//example how to use:
const cache = new TPCacheManager();

cache.lastRetrievedValue.catch(
  err=>{
    console.log("As expected, no value has been set",err);
  }
);
cache.setItem("doesnt matter, you ignore all parameters here")
.catch(err=>console.error("Oops, something went wrong setting an item:",err));

cache.lastRetrievedValue
.catch(
  err=>
    console.log("Value still not set, setItem does not do this in your code",err)
);

cache.getItem("doesnt matter, you are ignoring parameters here")
.then(
  value=>
    console.log("Value is undefined because getItem resolves to undefined",value)
);

cache.lastRetrievedValue
.then(
  value=>
    console.log("Ok, I have value because getItem has set it:",value)
);
//you can repeat cache.lastRetrievedValueor cache.theVal() without connecting to
//  memcached because you stored the promise

答案 1 :(得分:1)

兄弟......你真的会从阅读这篇文章中受益。每个使用promises的节点程序员都会。 https://medium.com/@brianalois/error-handling-in-node-javascript-suck-unless-you-know-this-2018-aa0a14cfdd9d

相关问题