Vue.js 学习笔记十四:Promise 之介绍和基本用法

目录

什么是 Promise

Promise 的基本用法


JavaScript 的执行环境是单线程

所谓单线程,是指 JS 引擎中负责解释和执行 JavaScript 代码的线程只有一个,也就是一次只能完成一项任务,这个任务执行完后才能执行下一个,它会「阻塞」其他任务。这个任务可称为主线程。

异步模式可以一起执行多个任务

常见的异步模式有以下几种:

  • 定时器

  • 接口调用

  • 事件函数

js 中常见的接口调用方式,有以下几种:

  • 原生 ajax

  • 基于 jQuery 的 ajax

  • Fetch

  • Promise

  • axios

多次异步调用的依赖分析

  • 多次异步调用的结果,顺序可能不同步。

  • 异步调用的结果如果存在依赖,则需要嵌套。

在 ES5 中,当进行多层嵌套回调时,会导致代码层次过多,很难进行维护和二次开发。而且会导致回调地狱的问题。ES6 中的 Promise 就可以解决这两个问题。

什么是 Promise

ES6 中的 Promise 是异步编程的一种方案。从语法上讲,Promise 是一个对象,它可以获取异步操作的消息。

Promise 对象, 可以将异步操作以同步的流程表达出来

使用 Promise 主要有以下好处:

  • 可以很好地解决回调地狱的问题(避免了层层嵌套的回调函数)。

  • 语法非常简洁。Promise 对象提供了简洁的 API,使得控制异步操作更加容易。

回调地狱的举例

假设买菜、做饭、吃饭都是异步的。

但真实的场景中,实际的操作流程是:买菜成功之后,才能开始做饭。做饭成功后,才能开始吃饭。这里面就涉及到了多层嵌套调用,也就是回调地狱。

Promise 的基本用法

使用 new 实例化一个 Promise 对象,Promise 的构造函数中传递一个参数。这个参数是一个函数,该函数用于处理异步任务。

并且传入两个参数:resolvereject,分别表示异步执行成功后的回调函数和异步执行失败后的回调函数。

通过 promise.then() 处理返回结果。这里的 promise 指的是 Promise 实例。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Promise 的基本用法</title>
	</head>
	<body>
		<script type="text/javascript">
			
			const runAsync = () => {
				// 第一步:model层的接口封装
				let promise = new Promise((resolve, reject) => {								
					// 这里做异步任务(比如 ajax 请求接口,这里暂时用定时器代替)
					setTimeout(() => {
						 // 接口返回的数据
						const data = { code: 200, msg:'hello world' }
						if (data.code === 200) {
							// 接口请求成功时调用
							resolve(data)
						} else {
							// 接口请求失败时调用
							reject({ code: 500, msg: 'network error' })
						}					
					}, 1000)
				})
				// 第二步:业务层的接口调用。这里的 res 就是 从 resolve 和 reject 传过来的,也就是从接口拿到的数据
				.then(res => {
					// 从 resolve 获取正常结果
					console.log(res)
				})
				.catch(res => {
					// 从 reject 获取异常结果
					console.log(res)									
				})
				return promise
			}	
            runAsync()
		</script>
	</body>
</html>

上方代码中,当从接口返回的数据data.code的值不同时,可能会走 resolve,也可能会走 reject,这个由你自己的业务决定。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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、付费专栏及课程。

余额充值