demo1:
var MongoClient = require('mongodb').MongoClient;
var count = 0;
var promise1 = new Promise(function(resolve, reject) {
MongoClient.connect('mongodb://localhost:27017/zuckjet', function(err, db) {
if (db) {
var collection = db.collection('users');
collection.find({}).toArray(function(err, docs) {
resolve(docs);
});
}
if (err) {
reject(err);
}
});
});
promise1.then(function(data) {
setTimeout(function() {
console.log(++count);
}, 5000);
}).then(function(res) {
console.log('second function begin to print');
console.log(count);
})
上述代码输出效果为:
second function begin to print
0
1 //也许5秒后输出
dem02:
var MongoClient = require('mongodb').MongoClient;
var count = 0;
var promise1 = new Promise(function(resolve, reject) {
MongoClient.connect('mongodb://localhost:27017/zuckjet', function(err, db) {
if (db) {
var collection = db.collection('users');
collection.find({}).toArray(function(err, docs) {
resolve(docs);
});
}
if (err) {
reject(err);
}
});
});
promise1.then(function(data) {
new Promise(function(resolve, reject) {
setTimeout(function() {
console.log(++count);
resolve(count);
}, 5000);
});
}).then(function(res) {
console.log('second function begin to print');
console.log(res);
console.log(count);
})
上述代码输出以下:
second function begin to print
undefined
0
1 //约莫5秒后输出
demo3:
var MongoClient = require('mongodb').MongoClient;
var count = 0;
var promise1 = new Promise(function(resolve, reject) {
MongoClient.connect('mongodb://localhost:27017/zuckjet', function(err, db) {
if (db) {
var collection = db.collection('users');
collection.find({}).toArray(function(err, docs) {
resolve(docs);
});
}
if (err) {
reject(err);
}
});
});
promise1.then(function(data) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log(++count);
resolve(count);
}, 5000);
});
}).then(function(res) {
console.log('second function begin to print');
console.log(res);
console.log(count);
})
上述代码输出效果以下:
1 //约莫五秒输出
second function begin to print
1
1
总结以下:
在形如:promise.then(…语句1…).then(…语句2…)中,
语句1中假如不运用return语句,语句2中没法接收到语句1中的参数
语句1中假如返回的是promise,语句2会守候语句1的resolve参数通报过来