1.Promise用法

  1. function silentLogin(){
  2. return new Promise(async (resolve,reject) => {
  3. let res = await apiLogin({'data':totalData.resdatapost,})
  4. if(res.code ==200){
  5. resolve(res.data);
  6. }else{
  7. reject(res.data);
  8. }
  9. })
  10. }
  11. silentLogin().then(res =>{}).catch(err =>{})

2.手写Promise

  1. function MyPromise(executor) {
  2. this.status = 'padding' // 定义初始状态
  3. this.value = undefined // 定义初始值
  4. this.onResolvedCallbacks = [] // 存放成功的回调
  5. this.onRejectedCallbacks= [] // 存放失败的回调
  6. let resolve = (value) => {
  7. if (this.status === 'padding') {
  8. this.status = 'resolve'
  9. this.value = value
  10. // 依次将对应的函数执行
  11. this.onResolvedCallbacks.forEach(fn=>fn());
  12. }
  13. }
  14. let reject = (value) =>{
  15. if (this.status === 'padding') {
  16. this.status = 'reject'
  17. this.value = value
  18. // 依次将对应的函数执行
  19. this.onRejectedCallbacks.forEach(fn=>fn());
  20. }
  21. }
  22. try {
  23. executor(resolve, reject)
  24. } catch (reason) {
  25. reject(reason);
  26. }
  27. }
  28. // 定义 then 方法
  29. MyPromise.prototype.then = function(onResolve, onReject) {
  30. switch(this.status){
  31. case 'padding':
  32. //如果promise的状态是 pending,需要将 onFulfilled 和 onRejected 函数存放起来,
  33. //等待状态确定后,再依次将对应的函数执行
  34. this.onResolvedCallbacks.push(() => {
  35. onResolve(this.value)
  36. });
  37. this.onRejectedCallbacks.push(() => {
  38. onReject(this.value)
  39. });
  40. break;
  41. case 'resolve' :
  42. onResolve(this.value)
  43. break;
  44. case 'reject':
  45. onReject(this.value)
  46. break;
  47. default:
  48. }
  49. }
  50. //测试
  51. new MyPromise((resolve, reject) => {
  52. setTimeout(() => {
  53. resolve('成功')
  54. },1500)
  55. })
  56. .then(res => {
  57. console.log('res',res)
  58. }, err => {
  59. console.log('err',err)
  60. })

3.Promise.all用法

  1. Promise.all([p3,p1,p2]).then(res =>{
  2. console.log(444,res)
  3. })

4.手写Promise.all

  1. function myPromiseAll(promises){
  2. return new Promise((resolve,reject) => {
  3. if(!Array.isArray(promises)){
  4. throw new TypeError("promises must be an array but it resolved to " + typeof(promises))
  5. }
  6. let result = []
  7. let count = 0
  8. promises.forEach((item,index) => {
  9. item.then((res) =>{
  10. result[index] = res
  11. count++
  12. if(count === promises.length){
  13. resolve(result)
  14. }
  15. },
  16. (err) =>{
  17. reject(err)
  18. }
  19. )
  20. })
  21. })
  22. }
  1. // 测试Promise.All
  2. const p1 = new Promise((reslove,reject)=>{
  3. setTimeout(function(){
  4. reslove(1)
  5. },1000)
  6. })
  7. const p2 = new Promise((reslove,reject)=>{
  8. setTimeout(function(){
  9. reslove(2)
  10. },2000)
  11. })
  12. const p3 = new Promise((reslove,reject)=>{
  13. setTimeout(function(){
  14. reslove(3)
  15. },3000)
  16. })
  17. myPromiseAll([p3,p1,p2]).then(res=>{
  18. console.log(res) //[3,1,2]
  19. })