Promise有几种状态? pending fulfilled rejected
    Promise有哪些方法? resolve reject
    Promise有哪些属性? value reason
    Promise有一个then方法

    1. class Promise {
    2. constructor (fn){
    3. this.state = "pending" //promise的状态
    4. this.value = undefined //resolve函数传递的参数
    5. this.reason = undefined //reject函数传递的参数
    6. //resolve函数将promise的状态改为fulfilled
    7. let resolve = value =>{
    8. if(this.state === 'pending'){
    9. this.state = 'fulfilled'
    10. this.value = value
    11. }
    12. }
    13. //resolve函数将promise的状态改为fulfilled
    14. let reject = value =>{
    15. if(this.state === 'pending'){
    16. this.state = 'reject'
    17. this.reason = value
    18. }
    19. }
    20. //让构造函数入参的函数立马执行
    21. try {
    22. fn (resolve,reject)
    23. } catch (e) {
    24. reject (e)
    25. }
    26. }
    27. //Promise的then方法入参两个函数,根据当前promise对象的state状态信息,决定是成功的回调函数执行还是失败的回调函数执行
    28. then(onFulfilled,onRejected) {
    29. switch (this.state) {
    30. case 'fulfilled':
    31. onFulfilled(this.value)
    32. break
    33. case 'rejected':
    34. onRejected(this.reason)
    35. break
    36. default:
    37. }
    38. }
    39. }
    40. //1.Promise是一个构造函数,需要入参一个函数,该函数的参数需要入参两个函数,而且该函数是立马执行的
    41. //2.Promise有三个状态:pending进行中 fulfilled成功 rejected失败
    42. //3.Promise有两个值:value是promise成功之后返回的值,reason是promise失败之后返回的原因
    43. //4.Promise有两个函数:resolve用于处理成功的函数,reject用于处理失败的函数
    44. //5.Promise的then方法可以入参两个函数,第一个是promise成功的回调,第二个是promise失败的回调
    45. var p = new Promise(function(resolve,reject){
    46. resolve(666);
    47. })
    48. p.then(function(res){
    49. console.log(res)
    50. })

    image.png

    1. lass Promise {
    2. constructor(fn) {
    3. this.state = "pending";
    4. this.value = null;
    5. this.reason = null;
    6. this.then = function (onFulfilled, onRejected) {
    7. //执行then方法的时候,需要查看Promise的状态,如果Promise执行成功,需要执行成功的的回调;如果Promise失败,需要执行Promise失败的回调
    8. switch (this.state) {
    9. case 'fulfilled':
    10. onFulfilled(this.value);
    11. break;
    12. case 'reject':
    13. onRejected(this.reason);
    14. break;
    15. }
    16. };
    17. let resolve = value => {
    18. if (this.state === 'pending') {
    19. this.state = "fulfilled";
    20. this.value = value;
    21. }
    22. }
    23. let reject = reason => {
    24. if (this.state === 'pending') {
    25. this.state = "reject";
    26. this.reason = reason;
    27. }
    28. }
    29. //执行fn函数
    30. try {
    31. fn(resolve, reject)
    32. } catch (e) {
    33. reject(e)
    34. }
    35. }
    36. }
    37. var p = new Promise(function (resolve, reject) {
    38. console.log("22222")
    39. resolve("小明");
    40. })
    41. //Promise.then方法接收两个函数做为参数
    42. //第一个函数参数是Promise成功的回调
    43. //第二个函数参数是Promise失败的回调
    44. p.then((msg) => {
    45. console.log(msg,"AAAAAAAAAA")
    46. }, (err) => {
    47. console.log(err,"BBBBBBBBBBBBBBB");
    48. })

    image.png