NodeJs 의 callback 작업 Promise 화
mongoose
는 NodeJs 아래 MongoDB 의 ORM 라 이브 러 리 다.이 라 이브 러 리 를 사용 하면 DB 부터 표 (collection) 까지 만 들 필요 가 없습니다.프로젝트 에서 만 정의 Model
.다음은 몬 고 스 의 데이터 베 이 스 를 조작 하 는 지옥 (callback hell) 을 쉽게 풀 수 있 는 방법 을 보 여 주 는 코드 입 니 다.
이전 Petshop 코드 는 여기 있 습 니 다.
Promise 스위치 열기
mongoose
Promise 에 대한 지원 이 시작 되 었 습 니 다. 명확 한 Promise 라 이브 러 리 만 지정 하면 됩 니 다.var mongoose = require('mongoose'),
Promise = require('bluebird');
원래 모든 model 의 정 의 는 mongoose 라 이브 러 리 를 도입 한 다음 에 매번 mongoose 라 이브 러 리 에 Promise 라 이브 러 리 를 지정 하 는 것 이 너무 복잡 합 니 다.그래서 추상 적 인 코드 는 models 디 렉 터 리 에 base 디 렉 터 리 를 만 든 다음 에 index. js 파일 을 추가 합 니 다.
//petshop/server/models/index.js
var mongoose = require('mongoose'),
Promise = require('bluebird');
mongoose.Promise = Promise;
module.exports = mongoose;
그리고 model 의 정 의 는 모두 export 로 Promise 를 추가 한 mongoose 입 니 다.
var mongoose = require('./base'),
bcrypt = require('bcrypt-nodejs');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username: {type: String, unique: true, required: true},
password: {type: String, required: true}
});
...
module.exports = mongoose.model('User', userSchema);
이렇게 해서 base 디 렉 터 리 에 있 는 mongoose 정 의 를 사용 한 model 은 모두 Promise 의 능력 을 갖 추 었 다.
업데이트 찾기 등 방법 을 호출 할 때 는 다음 과 같 아야 합 니 다.
User.findOne({ username: username }).exec().then(function (u) {
if (!u) {
done(null, false);
return;
}
var verifyPasswordAsync = Promise.promisify(u.verifyPassword, { context: u });
verifyPasswordAsync(password).then(function (match) {
console.log('password match ' + match);
if (!match) {
console.log('is match ' + match);
done(null, false);
} else {
done(null, u);
}
});
}).catch(function (err) {
done(err);
});
설명 은 다음 과 같다. 첫 번 째 줄 코드
User.findOne({ username: username }).exec()
는 exec 호출 후 Promise 를 되 돌려 주 었 다.뒤에 Promise 의 then 방법 을 사용 하여 Promise 방식 을 순서대로 호출 하고 이상 처 리 를 시작 할 수 있 습 니 다.단독 promise 화 방법
mongoose 에 내 장 된 Promise 지원 이 어떤 방법 을 완성 하지 못 할 때 bluebird 라 이브 러 리 를 따로 사용 하여 이 방법 을 단독으로 사용 하여 promise 화 할 수 있 습 니 다.예 를 들 어 상례
u.verifyPassword
코드:userSchema.methods.verifyPassword = function (password, callback) {
bcrypt.compare(password, this.password, function (err, match) {
if (err) {
return callback(err);
}
callback(null, match);
});
};
단독 promise 화
verifyPassword
방법:var verifyPasswordAsync = Promise.promisify(u.verifyPassword, { context: u });
이후 사용:
verifyPasswordAsync(password).then(function (match) {
console.log('password match ' + match);
if (!match) {
console.log('is match ' + match);
done(null, false);
} else {
done(null, u);
}
});
Promise 화의 일반 원칙
위의 예 에 대하 여 여기 서 약간 설명 하 다.Promise 화 할 때 사용 하 는 것 은
bluebird
라 이브 러 리 입 니 다.아래 에 사 용 된 예 코드 는 다음 과 같다.
function Dog(name) {
this.name = !name ? 'Tiger': name;
}
Dog.prototype.bite = function(target, cb){
console.log(this.name + ' bite ' + target);
cb(null, target);
};
Promise 대상 화
Promise 화 대상 사용
promisifyAll
방법.var Promise = require('bluebird');
var d = Promise.promisifyAll(new Dog());
d.biteAsync('hellokitty');
출력:
Tiger bite hellokitty
메모: Promise 화 후 호출 방법 은
Async
접 두 사 를 붙 여야 합 니 다.bite
=> biteAsync
。 Promise 화 방법
Promise 화 는 반전 이 있 는 방법 이다.이 Promise 가 되 돌아 온 결 과 는 정확 한 상황 에서 얻 은 값 을 되 돌려 주 는 것 이다.
var someDog = new Dog("small");
var otherDog = new Dog("big");
var proDog = Promise.promisify(someDog.bite, {context: otherDog});
proDog('YOU').then(function(target) {
console.log('then ' + target);
walk();
})
Promise 에서 한 가지 방법 을 말 할 때 context 를 지정 하 는 지 아 닌 지 를 고려 해 야 합 니 다.상례 에서 context 를 지정 하지 않 으 면 오류 가 발생 할 수 있 습 니 다.일반적으로 require 가 도입 한 라 이브 러 리 의 방법 이 라면 context 를 지정 할 필요 가 없 지만 부분 변 수 는 제정 해 야 합 니 다.context 를 지정 한 후 방법
this
이 가리 키 는 문맥 이 바로 이 context 대상 입 니 다.총결산
Promise 화 이후 지옥 으로 돌아 가 는 문 제 는 잘 해결 됐다.그러나 프로젝트 의 크기 와 리 셋 깊이 를 고려 해 Promise 화 여 부 를 결정 해 야 한다.Promise 는 코드 양 을 늘 리 고 학습 곡선 도 있 기 때문이다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.