Last active
January 4, 2016 02:39
-
-
Save ayapi/8556997 to your computer and use it in GitHub Desktop.
タイムアウト処理をdeferredでゃる練習 コンソールで「node requestTimeoutDeferred 0」って打ったら、
loadイベントがタイムアウトょり早く発火した時の動き
コンソールで「node requestTimeoutDeferred 1」って打ったら、
loadイベントが発火するょり前にタイムアウトの時間がきちゃった時の動き
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var deferred = require('deferred'); | |
var Backbone = require('backbone'); | |
var _ = require('lodash'); | |
var timer = [ | |
{load: 1000, timeout: 2000}, | |
{load: 3000, timeout: 2000} | |
]; | |
var Sample = Backbone.Model.extend({ | |
initialize: function(){ | |
this.setTimer(); | |
this.setPromiseBehavior(); | |
this.setDelayedTrigger(); | |
}, | |
setTimer: function(){ | |
var selector = process.argv[2]; | |
if(!timer[selector]){ | |
throw new Error('Invalid timer selection'); | |
} | |
this.timer = timer[selector]; | |
}, | |
setPromiseBehavior: function(){ | |
var promise = this.getPromise(); | |
promise.then( | |
function(){ | |
console.log('loaded'); | |
console.log(arguments); | |
}, | |
function(){ | |
console.log('error'); | |
console.log(arguments); | |
} | |
); | |
}, | |
setDelayedTrigger: function(){ | |
_.delay( | |
this.trigger.bind(this, 'load', {status: 200}), | |
this.timer.load | |
); | |
_.delay( | |
this.trigger.bind(this, 'timeout', 'Request timeout'), | |
this.timer.timeout | |
); | |
}, | |
getPromise: function(){ | |
var def = deferred(); | |
this.once('timeout', function(message){ | |
def.reject(new Error(message)); | |
}); | |
this.once('load', def.resolve); | |
return def.promise; | |
} | |
}); | |
new Sample(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment