1:异步操作(自己写回调来传入)
1 function requestData(url, successCallback, failureCallback) { 2 setTimeout(() => { 3 if (url === "http://www.baidu.com") { 4 console.log('成功了'); 5 const names = ['tyy', 'tsf'] 6 successCallback(names) 7 } else { 8 let msg = "强求url错误" 9 failureCallback(msg) 10 } 11 }, 3000) 12 } 13 requestData("http://www.baidu.com", (res) => { 14 console.log(res); 15 }, err => { 16 console.log(err); 17 })
但是这种方案有很多缺点:需要自己设计回调函数,回调函数的名称,对不同的人使用不太方便
2:Promise-----ES6新增的,是一个类
Promise的基本使用
1 function foo() { 2 return new Promise((resolve, reject) => { 3 //resolve("success message") 4 reject("failure message") 5 6 }) 7 } 8 const fooPromise = foo() 9 //then方法传入的回调函数, 10 //>第一个回调函数会在Promise执行resolve函数时被回调 //>第二个传入的回调函数会在Promise执行reject函数时被回调 11 fooPromise.then((res) => { 12 console.log(res); 13 14 }, (err) => { 15 console.log(err); 16 17 }) 18 //传入的函数被称之为 exectutor 成功的时候回调resolve 失败的时候调用reject 19 const promise = new Promise((resolve, reject) => { 20 // resolve() 21 // reject() 22 }) 23 promise.then(() => { 24 25 }) 26 promise.catch(() => { 27 28 })
异步请求的Promise 对第一个实现进行重构
1 function requestData(url, successCallback, failureCallback) { 2 //异步请求代码会被放在exectutor中 3 return new Promise((resolve, reject) => { 4 setTimeout(() => { 5 if (url === "http://www.baidu.com") { 6 const names = ['tyy', 'tsf'] 7 resolve(names) 8 } else { 9 let msg = "请求url错误" 10 reject(msg) 11 } 12 }, 1000) 13 14 }) 15 } 16 const promise = requestData("http://www.baidu.com") 17 promise.then((res) => { 18 console.log('请求成功:', res); 19 }, (msg) => { 20 console.log('请求失败:', msg); 21 22 })
3: Promise使用过程中有三个状态
pending:待定
fulfilled:已兑现
rejected:已拒绝
1 //注意:Promise状态一旦确定,便不可以再更改 2 new Promise((resolve, reject) => { 3 //pending 4 console.log('pending'); 5 reject() 6 //resolve() 7 }).then( 8 //fulfilled 9 (res) => { 10 console.log('res:', res); 11 }, 12 //rejected 13 (err) => { 14 console.log('err:', err); 15 })
4:Promise的resolve详解
1 //1:传递的参数是基本数据或者对象 2 new Promise((resolve, reject) => { 3 resolve({ 4 name: 'tyy' 5 }) 6 }).then( 7 res => { 8 console.log('res', res); 9 }, 10 err => { 11 console.log('err:', err); 12 } 13 )
1 //2:传递的参数是一个Promise类 具体执行会看newPromise里面的结构 2 const newPromise = new Promise((resolve, reject) => { 3 reject() 4 5 }) 6 new Promise((resolve, reject) => { 7 resolve(newPromise) 8 }).then( 9 res => { 10 console.log('res', res); 11 }, 12 err => { 13 console.log('err:', err); 14 } 15 )
1 //3:传递的是一个对象,并且这个对象有then方法,那么会执行改then方法,并更具then方法的结果来决定Promise的状态 2 3 new Promise((resolve, reject) => { 4 const obj = { 5 then: function(resolve, reject) { 6 // resolve('我是obj里面的then') 7 reject("我是obj里面的reject") 8 } 9 } 10 resolve(obj) 11 }).then( 12 res => { 13 console.log('res', res); 14 }, 15 err => { 16 console.log('err:', err); 17 } 18 )