Promisify 하고자 하는 함수의 조건?
1. 마지막 전달 인자로 callback 함수를 전달 받는 함수여야 한다.
ex)
(1) function func(arg1, arg2, callback) - O
(2) function func(arg1, arg2, arg3) - X
2. 1번이 성립한다는 가정하에, callback의 첫번째 전달인자가 err, 두번째가 result 여야 한다.
ex)
(1) function callback(err, result) - O
(2) function callback(err) - O
(3) function callback(result) - X
-------------------------------------------------------------------------------------------------
const Promise = require('bluebird');
function myCallback(err, result) {
if (err) {
console.log('Error msg : ' + err);
} else {
console.log('Not Error Result : ' + result);
}
}
function myFunc(arg1, arg2, myCallback) {
if (arg1 == arg2) {
myCallback(null, 'arg1, arg2 are same');
} else {
myCallback(new Error('Error!!!!!'));
}
}
var promisifiedMyFunc = Promise.promisify(myFunc);
//2 ,3 not same, then 'in catch!'
promisifiedMyFunc(2, 3).then((result) => {
console.log('in then');
}).catch((err) => {
console.log('in catch');
});
//2 ,2 same, then 'in then!'
promisifiedMyFunc(2, 2).then((result) => {
console.log('in then');
}).catch((err) => {
console.log('in catch');
});
//if myCallback has not a result? only has an err ?? , can we use a myFunc by promisify's parameter ??
//let's check this!
function myCallback2(err) {
if (err) {
console.log('Error msg : ' + err);
}
}
function myFunc2(arg1, arg2, myCallback2) {
if (arg1 == arg2) {
myCallback2();
} else {
myCallback2(new Error('Error!!!!!'));
}
}
var promisifiedMyFunc2 = Promise.promisify(myFunc2);
// //in case of fail
promisifiedMyFunc2(2, 3).then(() => {
console.log('in then');
}).catch((err) => {
console.log('in catch');
});
//in case of success
promisifiedMyFunc2(2, 2).then(() => {
console.log('in then');
}).catch((err) => {
console.log('in catch');
});
'Web' 카테고리의 다른 글
SSO 인증방식. (0) | 2017.03.13 |
---|---|
쿠키(Cookie) 와 세션(Session) 개념 (0) | 2017.03.13 |
Promise.promisify (0) | 2017.01.06 |
[Redux] 내가 만든 세미나 자료 파일 (리덕스정리) (0) | 2016.11.29 |
[React_Redux] 내가 만든 Todo App과 Redux Sample App 프로젝트 (0) | 2016.11.29 |