영어 공부 한답시고 맨날 영어 제목 달려고 노력하는데, 항상 맞는 표현인지 모르겠네요..
아무튼, 저런 작업을 어떻게 처리할 까 고민하던 중 runner.js 파일에서 비슷한 일을 하고 있음이 기억나 한번 코드를 찾아 봤습니다.
var ret = fixture.runTest(this);
fixture.endTime = new Date();
// if we get a deferred back from the test runner, we know we're
// gonna wait for an async result. It's up to the test code to trap
// errors and give us an errback or callback.
if(ret instanceof doh.Deferred){
tg.inFlight++;
ret.groupName = groupName;
ret.fixture = fixture;
ret.addErrback(function(err){
doh._handleFailure(groupName, fixture, err);
});
// 작업이 끝난 뒤, 처리해야 할 부분.
var retEnd = function(){
if(fixture["tearDown"]){ fixture.tearDown(doh); }
tg.inFlight--;
if((!tg.inFlight)&&(tg.iterated)){
doh._groupFinished(groupName, !tg.failures);
}
doh._testFinished(groupName, fixture, ret.results[0]);
if(doh._paused){
doh.run();
}
}
// TimeOut을 설정하는 부분 이 시간이 지나도록 작업이 끝나지 않았다면,
// Err를 발생시킵니다.
var timer = setTimeout(function(){
// ret.cancel();
// retEnd();
ret.errback(new Error("test timeout in "+fixture.name.toString()));
}, fixture["timeout"]||1000);
ret.addBoth(function(arg){
clearTimeout(timer);
retEnd();
});
if(ret.fired < 0){
doh.pause();
}
return ret;
}
단, 이런 방법으로 처리하기 위해서는 여기서 쓰이는 runTest() 함수의 형태를 갖춰야 합니다.
deferred 를 리턴해야 하고,
조건이 완료되면 deferred.callback(true) 도 호출해 줘야 하고요..
다음 코드 처럼요..
function asncFunction() {
var d = new doh.Deferred();
setTimeout(function() {
d.callback(true); // 작업 완료.. 를 의미.
}, 100);
return d;
}
아무튼 deferred 참 요긴하네요...
결론은, 동기적으로 처리하고 싶은 비동기 함수는,
deferred 인스턴스를 반환 해야 합니다.
그리고 비동기 작업이 완료된 시점에서, deferred.callback(true) 를 호출해 줍니다.
물론, 에러가 발생하였다면 deferred.errback()을 호출해 줘야겠죠,
그리고 그런 경우 리턴된 deferred에 addCallback에서 동기적으로 처리할 다음 함수를 호출해 주는 거지요.
후후.. 간단하군요..
