Promise

含义:

Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大。它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对象。

实例化Promise

const p = new Promise();

 

接收一个参数,这个参数是一个函数,函数有两个参数resolve和reject,异步函数过后,p.then(),里面有两个回调函数,前面那个是成功后的,后面一个是失败时的,如果异步函数中调用resolve则调用第一个函数,否则调用第二个。

const p =new Promise(function (resolve,reject) {
  setTimeout(function () {
    // let data ='resolve成功';
    // resolve(data);
    let err='reject失败'
    
    reject(err)
    },1000)
  });
  p.then(function (value) { console.log(value); },function (reason) {
    console.error(reason);
    })

 

读取文件

const fs=require('fs');
​
const p=new Promise(function(resolve,reject){
​
fs.readFile("./chunxiao.mdd",(err,data)=>{
    if(err){
        reject(err)
    }else(
        resolve(data)
    )
})
})
p.then(function(value){
console.log(value.toString());
},function(reason){
    console.log('读取失败');
​
})

 

Ajax函数封装

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const xhr= new XMLHttpRequest();
        const p=new Promise((resolve,reject)=>{
            xhr.open('get','https://api.apiopen.top/getJoke');
        xhr.send();
        xhr.onreadystatechange=function(){
            if(xhr.readyState ===4){
                if(xhr.status>=200&xhr.status<300){
                    resolve(xhr.response);
​
                }else{
                    reject(xhr.status);
                }
            }
        }
        })
        p.then(function(value){
            console.log(value)
        },function (reason) {
            console.log(reason)
          })
    </script>
</body>
</html>

 

初试catch

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
const p =new Promise(function (resolve,reject) {
  setTimeout(function () {
    // let data ='resolve成功';
    // resolve(data);
    let err='catch失败'
    
    reject(err)
    },1000)
  });
//   
p.catch(function (reason) { 
    console.warn(reason);
 })
    </script>
</body>
</html>

 

catch总结:其实可以把catch看作是then的语法糖,里面就少了一个resolve的参数。

 

Promise.prototype.finally()

finally()方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。该方法是 ES2018 引入标准的。

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});

 

上面代码中,不管promise最后的状态,在执行完thencatch指定的回调函数以后,都会执行finally方法指定的回调函数。

实例(体现promise的好处)

通过新建一个 Promise 对象好像并没有看出它怎样 "更加优雅地书写复杂的异步任务"。我们之前遇到的异步任务都是一次异步,如果需要多次调用异步函数呢?例如,如果我想分三次输出字符串,第一次间隔 1 秒,第二次间隔 4 秒,第三次间隔 3 秒:

setTimeout(function () {
    console.log("First");
    setTimeout(function () {
        console.log("Second");
        setTimeout(function () {
            console.log("Third");
        }, 3000);
    }, 4000);
}, 1000);

 

这段程序实现了这个功能,但是它是用 "函数瀑布" 来实现的。可想而知,在一个复杂的程序当中,用 "函数瀑布" 实现的程序无论是维护还是异常处理都是一件特别繁琐的事情,而且会让缩进格式变得非常冗赘。

现在我们用 Promise 来实现同样的功能:

new Promise(function (resolve, reject) {
    setTimeout(function () {
        console.log("First");
        resolve();
    }, 1000);
}).then(function () {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log("Second");
            resolve();
        }, 4000);
    });
}).then(function () {
    setTimeout(function () {
        console.log("Third");
    }, 3000);
});

 

 

 

posted on 2020-10-27 21:23  娃哈哈a爽歪歪  阅读(111)  评论(0编辑  收藏  举报