2017-02-28 9 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. プロミスを入れるにはどのような方法が良いですか?すべての関数は約束を返す必要があります

  4. すべてthen関数私はbindを使用する必要がありますか?このような

    TODO:

create: function() { 
    this.get() 
     .then(remove) 
     .then(function() { 
      this.item = {}; // BUT this === undefined!! 
     }); 
} 
あなたはすべてのその後、コールバック関数内でバインドを使用する必要が
+1

それぞれの方法を変更して約束を返すだけの答えではありませんか?私は、あなたが「約束を入れる最善の方法は何ですか?」と言ったときに、あなたが何を求めているのか分かりません。あなたの非同期操作が約束を返すようにして、メソッドがそれらの非同期操作の1つを使用する場合は、約束を返します。 – jfriend00

+0

'//しかしこれは===未定義です!! ' - これは" this "がどのように動作するかに起因しています - それについての情報がたくさんあります - bindを使うよりもむしろ一つの回避策は古い' 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); 
});  
関連する問題