//the below function means that wrap the given node function
//Promise.promisify({}); 이거에 리턴값은 function 이다.
//아래와 같이 wrapping 된다.
// var test = function(arg1, arg2){
// return new Promise(executor); //(resolve, reject) => { }
// }
//
// myFunctionPromisified(2,4).then(result => { console.log('success result : ' + result)}).catch(err => {console.log(err)});
//promisify 가 무엇을 할까?
//우리의 node function의 callback 전달인자에다가, 자기가 만든걸 넣어주지않을까?
//node function 실행 -> 성공했으면 then 호출, 실패했으면 catch 호출
//promisify 가 node function의 callback 위치에다가, then 에 있는 함수를 넣거나, catch에 있는 함수를 넣거나..
//근데 아직 내부 로직을 안돌려보고 어떻게 yes or no를 알고서 callback 위치에 넣을까? 합리적 추론이 아니닷... 실패..
//그러면, 중간에 하나의 function을 더 두는거지... 예를들면?
//node function의 마지막 전달인자인 Callback은 내부 로직이 성공했으면 callback(null, result) 일 것이고
//실패했으면 callback(err) 를 호출할텐데,
//이게 약속되어있으니까..
//애초에 node function의 마지막 전달인자 callback을 promisify 측에서
//아래의 wrapCallbackFunction 형태로 바꿔치는거지..
//그래서, node function의 return값이 True 냐 false냐에 따라서, then에 등록한 callback을 실행할지, catch에 등록한 callback을 실행할지
//대신 결정해주는 거지..
//
//내가 생각하는 promisify 함수 모양새...가 그러면 어떻게 생겼을까? 한번해볼까..
//일단 전달인자는 args...., callback 을 전달인자로 받는 nodeFunction!
const Promise = require('bluebird');
function promisify(nodeFunction){
return function (args){
return new Promise((resolve, reject) => {
nodeFunction(args, function(err, result){
if(err){
reject(err);
}else{
resolve(result);
}
});
});
};
};
//돌아가나 해볼까?
var myFunction = function(arg, callback){
var result = arg * arg;
if(result == 0){
callback(new Error('result is zero'));
}else{
callback(null, result);
}
};
const myFunctionPromisified = promisify(myFunction);
myFunctionPromisified(0).then((result) => { console.log(result)}).catch(err => {console.log(err)});
//구웃 구웃 구웃 구웃 잘 돌아가넹..
//결국 promisify 는 위와 같이 생겼을것이고,
//사용법은 위와 같을 것이다...
//오홍!
'Web' 카테고리의 다른 글
쿠키(Cookie) 와 세션(Session) 개념 (0) | 2017.03.13 |
---|---|
bluebird 모듈의 promisify 조건은?? (0) | 2017.01.11 |
[Redux] 내가 만든 세미나 자료 파일 (리덕스정리) (0) | 2016.11.29 |
[React_Redux] 내가 만든 Todo App과 Redux Sample App 프로젝트 (0) | 2016.11.29 |
[펌] Webpack 입문 메뉴얼 링크 (0) | 2016.11.09 |