今天在學nodejs的時候,遇到一個錯誤;剛開始完全不知道說的是什么,為什么會出現這個錯誤
DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead;
因為我是調用數據的庫的方法中使用了then()方法;
User.findOne({
username: username//查詢條件
}).then(function (userInfo) {}
解決方法:
mongoose.Promise = global.Promise;
解釋:
Promise表示一個異步操作的最終結果。與Promise最主要的交互方法是通過將函數傳入它的then方法從而獲取得Promise最終的值或Promise最終被拒絕(reject)的原因。
ECMAScript 6 規范:
Promise 是一個對象, 是異步編程的一種解決方案,,從它可以獲取異步操作的消息;
語法學習:
狀態:
pending:初始狀態;
rejected:操作失敗;
fulfilled:操作成功;
Promise
對象的狀態改變,只有兩種可能:從pending
變為fulfilled
和從pending
變為rejected
。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
和 Promise.prototype.then
方法返回promise 對象, 所以它們可以被鏈式調用;Promise.prototype.catch
方法:
Promise.prototype.catch(onRejected);
Promise.prototype.then(onFulfilled, onRejected);
編寫一個promise函數,只需讓其返回一個promise即可。
基本用法:
Promise
構造函數接受一個函數作為參數,該函數的兩個參數分別是resolve
和reject
。它們是兩個函數,由 JavaScript 引擎提供,不用自己部署。
resolve
函數的作用是,將Promise
對象的狀態從“未完成”變為“成功”(即從 pending 變為 resolved),在異步操作成功時調用,並將異步操作的結果,作為參數傳遞出去;reject
函數的作用是,將Promise
對象的狀態從“未完成”變為“失敗”(即從 pending 變為 rejected),在異步操作失敗時調用,並將異步操作報出的錯誤,作為參數傳遞出去。
var promise = new Promise(function(resolve, reject) { // ... some code
if (/* 異步操作成功 */){ resolve(value); }
else { reject(error); }
});
promise.then(function(value) {// success},
function(error) {
// failure
});
eg:
var getJSON = function(url) {
var promise = new Promise(function(resolve, reject){
var client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
function handler() {
if (this.readyState !== 4) {
return; }
if (this.status === 200) {
resolve(this.response); }
else {
reject(new Error(this.statusText));
}
};
});
return promise;
};
getJSON("/posts.json").then(function(json) { console.log('Contents: ' + json); }, function(error) { console.error('出錯了', error); });