【ES6】Promise

Promise

回调地狱

const fs = require('fs');

fs.readFile('./a.txt', 'utf-8', (err, data) => {
  if(err) throw err;
  console.log(data);

  fs.readFile('./b.txt', 'utf-8', (err, data) => {
    if(err) throw err;
    console.log(data);

    fs.readFile('./c.txt', 'utf-8', (err, data) => {
      if(err) throw err;
      console.log(data);
    })
  })
})

Promise

Promise对象可以解决回调地狱的问题

Promise可以理解为一个容器,里面可以编写异步程序的代码

基本用法
const fs = require('fs');

//1、创建对象
let p = new Promise((resolve, reject) => {
  //把异步任务成功的结果传递给resolve函数,把失败的结果传递给reject函数
  fs.readFile('./a.txt', 'utf-8', (err, data) => {
   //读取文件的时候,没有错误err=null, 有错误err={} 
    err ? reject(err) : resolve(data);
  })
});

//2、获取成功失败结果
p.then(res => console.log(res), err => console.log(err));

Promise三种状态

pending fulfilled rejected

  • 最初状态pending, 等待中,此时promise的结果为undefined;

  • 当调用resolve(data)时, 状态变为 fulfilled

  • 当调用reject(err)时, 状态变为 error

  • 当达到最终的fulfilled或rejected时,promise的状态就不会再改变了(所以多次调用resolve,后面的resolve都无效,只取第一次)

    // 1、创建对象
    let p = new Promise((resolve, reject) => {
    resolve();
    resolve(123);//这次调用无效
    });

    // 2、获取成功失败结果
    p.then(res => console.log(res), err => console.log(err));

Promise同步异步?
console.log(1);

//new Promise属于同步代码
new Promise((resolve, reject) => {
  console.log(2);
  resolve(3);
  console.log(4);
}).then(res => console.log(res), err => console.log(err));//.then这里是异步的

console.log(5);

// 1 2 4 5 3
then的链式调用
const fs = require('fs');

let p1 = new Promise((resolve, reject) => {
  fs.readFile('./a.txt', 'utf-8', (err, data) => {
    err ? reject(err) : resolve(data);
  })
});

let p2 = new Promise((resolve, reject) => {
  fs.readFile('./b.txt', 'utf-8', (err, data) => {
    err ? reject(err) : resolve(data);
  })
});

let p3 = new Promise((resolve, reject) => {
  fs.readFile('./c.txt', 'utf-8', (err, data) => {
    err ? reject(err) : resolve(data);
  })
});

//前一个then返回一个Promise对象
//后一个then可以得到前一个Promise对象的成功状态的值
p1.then(r1 => {
  console.log(r1); //aaa
  return p2
}).then(r2 => {
  console.log(r2); //bbb
  return p3;
}).then(r3 => {
  console.log(r3); //ccc
})



const fs = require('fs');

function myReadFile(filename) {
  return p = new Promise((resolve, reject) => {
    fs.readFile(filename, 'utf-8', (err, data) => {
      err ? reject(err) : resolve(data);
    })
  })
}

//前一个then返回一个Promise对象
//后一个then可以得到前一个Promise对象的成功状态的值
myReadFile('./a.txt').then(r1 => {
  console.log(r1); //aaa
  return myReadFile('./b.txt');
}).then(r2 => {
  console.log(r2); //bbb
  return myReadFile('./c.txt');
}).then(r3 => {
  console.log(r3); //ccc
})

你可能感兴趣的:(es6,javascript,前端)