Promise应用

【1】基础应用——单次调用

const fs = require(‘fs‘);

//Promise初始化为:等待状态 pending

let promise = new Promise((resolve, reject) => {

console.log(‘start...‘);

//异步任务

fs.readFile(‘./callback/a.txt‘, ‘utf-8‘, function(err, data) {

if (err) return reject(err);

resolve(data);

    });

console.log(‘end...‘);

});

//then()实例方法 指定Promise对象状态改变时确定执行的操作

promise.then(data => {

console.log(data);

}, err => {

console.log(err);

});

【2】多次调用

【1】简单组合串行

let fs = require(‘fs‘);

//回调多次的问题

function read() {

fs.readFile(‘./callback/promise/a.txt‘, ‘utf8‘, function(err, data) {

if (err) return console.log(err);

console.log(data);

fs.readFile(‘./callback/promise/b.txt‘, ‘utf8‘, function(err, data) {

if (err) return console.log(err);

console.log(data);

        })

    });

}

read();

=========================================

【2】promise+then

function _read(path) {

return new Promise((resolve, reject) => {

fs.readFile(path, ‘utf8‘, function(err, data) {

if (err) return reject(err);

resolve(data);

        });

    });

}

_read(‘./callback/promise/a.txt‘).then((err) => {

console.log(err);

}, (data) => {

console.log(data);

});

_read(‘./callback/promise/b.txt‘).then((err) => {

console.log(err);

}, (data) => {

console.log(data);

});

=================================

【3】promise+then嵌套

_read(‘./callback/promise/a.txt‘).then((data) => {

console.log(data);

_read(‘./callback/promise/b.txt‘).then((data) => {

console.log(data);

    });

});

===================================

【4】链式调用

_read(‘./callback/promise/a.txt‘).then(data => {

console.log(data);

console.log(1);

return _read(‘./callback/promise/b.txt‘);

}, err => {

console.log(err);

}).then(data => {

console.log(data);

console.log(2);

}, err => {

console.log(err);

});

Peomise.all方法应用

//同时读取a.txt,b.txt, 返回的是所有结果

Promise.all([read(‘./callback/promise/a.txt‘), read(‘./callback/promise/b.txt‘)]).then((res) => {

console.log(res);

});

// res 返回的是全部文件结果

//race : 返回最先执行完的结果

//或者说:参数中谁的状态先改变,直接决定最后race()返回的promise实例状态

Promise.race([read(‘./callback/promise/b.txt‘), read(‘./callback/promise/a.txt‘)]).then((res) => {

console.log(res);

}, (error) => {

console.log(error);

});

catch语句

let promise = read(‘./callback/promise/ad.txt‘);

promise.then(data => {

console.log(data);

}, err => {

console.log(err);

});

promise = read(‘./callback/promise/ad.txt‘);

//捕获error

promise.then(data => {

console.log(data);

}).catch(err => {

console.log(err);

});