1. callback을 사용한 비동기 후처리

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var callApi = function(successCallback, failCallback){
        $.post('/user.do', $("#parameter").serialize())
        .done(function(response){
              successCallback(response);
          })
        .fail(function(xhr, status, err){
               failCallback(err);                    
        });
     }
 
 
//on button click
callApi(function(data){
                  alert("this is successCallback!");
                  if(data.alertMssage !== undefined){
                    alert(data.alertMssage);
                  }
            },
            function(err){
                alert("this is failCallback!");
                alert(err);
            });    
cs

 

2. promise 를 사용한 비동기 후처리

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var callApi = function(){
    return new Promise(function(resolve, reject){
                                $.post('/user.do', $("#parameter").serialize())
                                   .done((response)=>resolve(response))
                                   .fail((xhr, status, err)=>reject(err));
                               });
}
 
//on button click
callApi().then(function(data){
            alert("this is successCallback!");
            if(data.alertMssage !== undefined){
              alert(data.alertMssage);
            }
          }).catch(function(err){
              alert("this is failCallback!");
              alert("failed!");
          }); 
cs

 

promise에 대한 설명이 아래 링크에 워낙 잘 되어 있으므로 모든 설명은 생략.

설명이 매우 잘 되어있는 글

 

반응형

+ Recent posts