2017-02-28 71 views
2

我用角1.5和我做了一个工厂函数,它是返回一个文本对象是这样的:如何让模块模式的每个功能都有保证?

return { 
    item: null, 
    get: function() { 
    return item; 
    }, 
    create: function() { 
    if (this.get()){ 
     this.remove(); 
    } 

    this.item = {}; 
    }, 
    remove: function() { 
    var item = this.get(); 
    if (item) { 
     this.item = null; 
    } 
    }, 
    add: function() { 
    if (!this.get()) { 
     this.create(); 
    } 

    this.item.newprop = 'value'; 
    } 
} 
  1. 请不要问我改到函数声明。我想要一个拥有自己的动作(函数)和属性的对象。

  2. 这种模式(如get里面create等..)我没有从任何地方复制。所以我想知道是否有名字?处理函数黑盒子是最好的方法吗?

  3. 把Promise放在里面的最好方法是什么?所以每个函数都应该返回一个承诺

  4. then函数我需要使用bind ???

    待办事项这样的:

create: function() { 
    this.get() 
     .then(remove) 
     .then(function() { 
      this.item = {}; // BUT this === undefined!! 
     }); 
} 
+1

对于你的问题,为什么承诺的一部分是不是答案只是你修改每个方法来返回一个承诺?我不知道当你说“什么是最好的方式来承诺内部”时你可能会问什么?你让你的异步操作返回承诺,然后你如果一个方法使用这些异步操作之一,你返回他们的承诺。 – jfriend00

+0

'''但是这个=== undefined !!' - 这是由于“this”是如何工作的 - 大量的关于SO的信息 - 一个解决方法(而不是使用绑定)是旧的'var _this = this;'' - 或者使用arrow =>函数 –

+0

get方法中的'item'是指什么? – Bergi

回答

0

你必须使用绑定在每则回调函数:

var myModule = { 
    item: null, 
    get: function() {    
     return Promise.resolve(this.item); 
    }, 
    create: function() { 
     return this.remove().then(function() { 
      this.item = {}; 
     }.bind(this)); 
    }, 
    remove: function() { 
     return this.get().then(function(item) { 
      if (item) { 
       this.item = null; 
      } 
     }.bind(this));    
    }, 
    add: function() { 
     return this.get().then(function(item) { 
      return item || this.create(); 
     }.bind(this)).then(function() { 
      this.item.newprop = 'value'; 
     }.bind(this)); 
    } 
}     
// Let see it working: 
myModule.create().then(function() { 
    return myModule.get(); 
}).then(function(item) { 
    console.log("After create: ", item); 
    return myModule.remove(); 
}).then(function() { 
    return myModule.get(); 
}).then(function(item) { 
    console.log("After remove: ", item); 
    return myModule.add(); 
}).then(function() { 
    return myModule.get(); 
}).then(function(item) { 
    console.log("After add: ", item); 
});