promise.then()使用筆記

demo1:mongodb

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秒後輸出promise

dem02:ui

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秒後輸出code

demo3:io

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
1console

總結以下:
在形如:promise.then(...語句1...).then(...語句2...)中,function

  1. 語句1中若是不使用return語句,語句2中沒法接收到語句1中的參數require

  2. 語句1中若是返回的是promise,語句2會等待語句1的resolve參數傳遞過來im

相關文章
相關標籤/搜索