Promise

Promise

1. 有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。

2. Promise是来解决异步编程的( 代码如果一直嵌套【死亡地狱】,易读性很差)

Promise.resolve(‘foo’).then(res=>{

    Console.log(res) // foo

).then(res=>{

    每一个promise方法,都会系统自带一个return new promise

    Console.log(res) // undefined

)

上面的这个

和下面这个相等的

new Promise(resolve=>resolve(‘foo’)).then(res=>{

    Console.log(res)  // foo

})

 

例子:

const p1 = () => (new Promise((resolve, reject) => {

    console.log(1);

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

     console.log(2);

    const timeOut1 = setTimeout(() => {

     console.log(3);

     resolve(4);

    }, 0)

    resolve(5);

});

    resolve(6)

 

p2.then((arg) => {

    console.log(arg,'5555555');

});

 

}));

 

const timeOut2 = setTimeout(() => {

    console.log(8);  

    const p3 = new Promise(resolve => {

    resolve(9);

}).then(res => {  

    console.log(res);

})

}, 0)

    

p1().then((arg) => {

   console.log(arg,'66666');

})

console.log(10);

 

posted @ 2022-05-11 15:29  杨建鑫  阅读(22)  评论(0编辑  收藏  举报