어휴 deferred이라는게 큐구조의 연결리스트를 사용하면서


setTImeout 함수에 0을 넣음으로써


비동기성을 부여하는거구나..


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// # deferred
(function() {
    'use strict';
 
    var Deferred = ADUN.Deferred = ADUN.Class({
        TYPE: 'Deferred',
        EXTEND: null,
 
        init: function() {
            this._success   =   this._fail  =   this._next  =   this._id    = null;
            this._tail = this;
        },
 
        _add: function(queue) {
 
            // 큐 방식의 연결리스트 자료구조를 사용한다.
 
            // 마지막에 추가된 Deffered 객체._next => 마지막에 추가된 Deffered 객체
            this._tail._next = queue;
 
            // 꼬리는 항상 마지막에 추가된 Deffered 객체를 가리킨다.
            this._tail = queue;
 
            // 연결리스트에서 맨 처음 Deffered 객체 반환 (체이닝 기법?)
            return this;
        },
 
        next: function(func) {
            var queue = new ADUN.Deferred();
            queue._success = func;
            return this._add(queue);
        },
 
        error: function(func) {
            var queue = new ADUN.Deferred();
            queue._fail = func;
            return this._add(queue);
        },
 
        call: function(arg) {
            var received;
            var queue = this;
 
            console.dir(this);
 
            // error 건너뛰기
            while( queue && !queue._success ) {
                queue = queue._next;
            }
 
            if!(queue instanceof ADUN.Deferred ) ) {
                return;
            }
 
            try {
                received = queue._success(arg);
            } catch (e) {
                return queue.fail(arg);
            }
 
            if( received instanceof ADUN.Deferred ) {
 
            } else if( queue._next instanceof ADUN.Deferred ) {
                // 연결리스트에서 다음 객체가 Deferred의 인스턴스라면 진입.
                queue._next.call(received);
            }
 
        }
    });
 
    Deferred.next = function(func) {
        var queue = new ADUN.Deferred().next(func);
 
        // 타이머 함수를 이용하여 비동기성을 가진다.
        // (함수 스택이 클리어되었을때 실행된다.)
        queue._id = setTimeout(function() {
            queue.call();
        }, 0);
 
        return queue;
    }
})();
cs


1
2
3
4
5
6
7
ADUN.Deferred.next(function() {
        return 32
    }).next(function(n) {
        alert(n)
    }).next(function() {
        alert('hello')
    });
cs


setTimout 은 두번째 인자의 시간이 지난후 호출되는 타이머함수인데


니콜라스자카스 형님이 말씀하시기를 시간이 지난후 곧바로 호출되는게아니라


시간이 지난후 함수스택이 비어잇을경우 호출된다네.


고로 0을 너음으로써 비동기성을 부여하는군..