2016-03-22 4 views
0

Promiseが公式に仕様化されているので、次のスニペットの$q.defer()プロミス作成を$q(function (resolve, reject) {})コンストラクタ構文を代わりに使用するように変換するにはどうすればよいですか?

// Cancel any ongoing $http request so that only the most recent $http 
// callback gets invoked 
var canceller; 
function getThing(id) { 
    if (canceller) canceller.resolve(); 
    canceller = $q.defer(); 

    return $http.get('/api/things/' + id, { 
    timeout: canceller.promise 
    }); 
} 

$http docsからのFYI:timeoutは "ミリ秒単位で...、または解決したときに、要求を中止しなければならない約束。" である)

+0

あなたの目標は何か分かりません。あなたのコードはうまく動作しているので、何も変更する必要はありません。 – Bergi

+0

"*プロミスコンストラクタ構文を使用するには?*" - [**あなたはいません!**](http://stackoverflow.com/q/23803743/1048572) – Bergi

+0

ゴールはありません。単なる学問的なエクササイズ – thatmarvin

答えて

1

は、私はこのようにそれを行うだろう:

var canceller = null; 
function getThing(id) { 
    if (canceller) canceller(); 
    return Promise.resolve($http.get('/api/things/' + id, { 
    timeout: new Promise(function(resolve) { 
     canceller = resolve; 
    }) 
    })); 
} 

とにかくcanceller.rejectを使用したことがないと仮定しますので、次回にはresolve関数自体を呼び出すことができます。

+0

$ http.get()は約束を返すので、Promise.resolve()ラップは必要ないと思いますか? – thatmarvin

+0

@thatmarvin:公式に指定された 'Promise'のような光沢のある新しいものは返さないが、古い退屈なAngularJs約束:-) Angular promises(' 'new promise'の代わりに' $ q'') )もちろんそれを省略することができます。 – Bergi

+0

gotcha、受け入れました。非常に明白な今私はそれを見る、ありがとう! – thatmarvin

関連する問題