Vue.js 学习笔记十四:Promise 之 常用API:实例方法和对象方法

目录

Promise 常用API

实例方法

对象方法


Promise 常用API

实例方法

Promise 自带的API提供了如下实例方法:

  • promise.then():获取异步任务的正常结果。

  • promise.catch():获取异步任务的异常结果。

  • promise.finaly():异步任务无论成功与否,都会执行。

代码举例如下。

写法1:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>实例方法1</title>
    </head>
    <body>
        <script type="text/javascript">
            const queryData = () => {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        const data = { code: 200, msg: 'hello world' } // 接口返回的数据
                        if (data.retCode == 0) {
                            // 接口请求成功时调用
                            resolve(data);
                        } else {
                            // 接口请求失败时调用
                            reject({ code: 500, msg: 'network error' })
                        }
                    }, 1000)
                })
            }

            queryData()
                .then(data => {
                    // 从 resolve 获取正常结果
                    console.log('接口请求成功时,走这里');
                    console.log(data);
                })
                .catch(data => {
                    // 从 reject 获取异常结果
                    console.log('接口请求失败时,走这里');
                    console.log(data);
                })
                .finally(() => {
                    console.log('无论接口请求成功与否,都会走这里');
                })
        </script>
    </body>
</html>

写法2:(和上面的写法1等价)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>实例方法2</title>
    </head>
    <body>
        <script type="text/javascript">
            const queryData = () => {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        const data = { code: 200, msg: 'hello world' } // 接口返回的数据
                        if (data.retCode == 0) {
                            // 接口请求成功时调用
                            resolve(data);
                        } else {
                            // 接口请求失败时调用
                            reject({ code: 500, msg: 'network error' })
                        }
                    }, 1000)
                })
            }

            queryData()
                .then(
                    data => {
                        // 从 resolve 获取正常结果
                        console.log('接口请求成功时,走这里')
                        console.log(data)
                    },
                    data => {
                        // 从 reject 获取异常结果
                        console.log('接口请求失败时,走这里')
                        console.log(data)
                    }
                )
                .finally(() => {
                    console.log('无论接口请求成功与否,都会走这里')
                });
        </script>
    </body>
</html>

注意:写法1和写法2的作用是完全等价的。只不过,写法2是把 catch 里面的代码作为 then里面的第二个参数而已。

对象方法

Promise 自带的API提供了如下对象方法:

  • Promise.all():并发处理多个异步任务,所有任务都执行成功,才能得到结果。

  • Promise.race(): 并发处理多个异步任务,只要有一个任务执行成功,就能得到结果。

Promise.all() 代码举例

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Promise.all() 代码举例</title>
    </head>
    <body>
        <script type="text/javascript">
            /*
              封装 Promise 接口调用
            */
            const queryData = url => {
                return new Promise((resolve, reject) => {
                    let xhr = new XMLHttpRequest()
                    xhr.onreadystatechange = () => {
                        if (xhr.readyState != 4) {
                            return
                        }
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            // 处理正常结果
                            resolve(xhr.responseText)
                        } else {
                            // 处理异常结果
                            reject('服务器错误')
                        }
                    }
                    xhr.open('get', url)
                    xhr.send(null)
                })
            }

            const promise1 = queryData('http://localhost:8000/api1')
            const promise2 = queryData('http://localhost:8000/api2')
            const promise3 = queryData('http://localhost:8000/api3')

            Promise.all([promise1, promise2, promise3]).then(result => {
                console.log(result)
            })
        </script>
    </body>
</html>

Promise.race() 代码举例

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>Promise.race() 代码举例</title>
    </head>
    <body>
        <script type="text/javascript">
            /*
              封装 Promise 接口调用
            */
            const queryData = url => {
                return new Promise((resolve, reject) => {
                    let xhr = new XMLHttpRequest()
                    xhr.onreadystatechange = () => {
                        if (xhr.readyState != 4) {
                            return
                        }
                        if (xhr.readyState == 4 && xhr.status == 200) {
                            // 处理正常结果
                            resolve(xhr.responseText)
                        } else {
                            // 处理异常结果
                            reject('服务器错误')
                        }
                    }
                    xhr.open('get', url)
                    xhr.send(null)
                });
            }

            const promise1 = queryData('http://localhost:8000/api1')
            const promise2 = queryData('http://localhost:8000/api2')
            const promise3 = queryData('http://localhost:8000/api3')

            Promise.race([promise1, promise2, promise3]).then(result => {
                console.log(result)
            })
        </script>
    </body>
</html>

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
index.vue:201 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'type') at _callee$ (index.vue:201:1) at tryCatch (regeneratorRuntime.js:44:1) at Generator.eval (regeneratorRuntime.js:125:1) at Generator.eval [as next] (regeneratorRuntime.js:69:1) at asyncGeneratorStep (asyncToGenerator.js:3:1) at _next (asyncToGenerator.js:22:1) at eval (asyncToGenerator.js:27:1) at new Promise (<anonymous>) at eval (asyncToGenerator.js:19:1) at VueComponent.handleNodeClick (index.vue:227:1) _callee$ @ index.vue:201 tryCatch @ regeneratorRuntime.js:44 eval @ regeneratorRuntime.js:125 eval @ regeneratorRuntime.js:69 asyncGeneratorStep @ asyncToGenerator.js:3 _next @ asyncToGenerator.js:22 eval @ asyncToGenerator.js:27 eval @ asyncToGenerator.js:19 handleNodeClick @ index.vue:227 handleCurrentChange @ index.vue:197 invokeWithErrorHandling @ vue.runtime.esm.js:3971 invoker @ vue.runtime.esm.js:1188 invokeWithErrorHandling @ vue.runtime.esm.js:3971 Vue.$emit @ vue.runtime.esm.js:2874 eval @ element-ui.common.js:1116 eval @ vue.runtime.esm.js:4097 flushCallbacks @ vue.runtime.esm.js:4019 Promise.then(异步) timerFunc @ vue.runtime.esm.js:4044 nextTick @ vue.runtime.esm.js:4109 queueWatcher @ vue.runtime.esm.js:3346 Watcher.update @ vue.runtime.esm.js:3584 Dep.notify @ vue.runtime.esm.js:710 reactiveSetter @ vue.runtime.esm.js:4380 proxySetter @ vue.runtime.esm.js:5158 handleCurrentChange @ element-ui.common.js:1069 invokeWithErrorHandling @ vue.runtime.esm.js:3971 invoker @ vue.runtime.esm.js:1188 invokeWithErrorHandling @ vue.runtime.esm.js:3971 Vue.$emit @ vue.runtime.esm.js:2874 onPagerClick @ element-ui.common.js:547 invokeWithErrorHandling @ vue.runtime.esm.js:3971 invoker @ vue.runtime.esm.js:1188 original_1._wrapper @ vue.runtime.esm.js:7265
06-12

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

stary1993

你的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值