promise.then()运用笔记

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. 语句1中假如不运用return语句,语句2中没法接收到语句1中的参数

  2. 语句1中假如返回的是promise,语句2会守候语句1的resolve参数通报过来

    原文作者:唐僧洗头爱飘柔
    原文地址: https://segmentfault.com/a/1190000010171711
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞