Promise 4种常规用法

Promise 4种常规用法

new Promise(funA).then(funB).catch(funC)
new Promise(funA).then(funB, funC)
new Promise(funA).then(funB).then(funC)
new Promise(funA).then(funB1, funB2).then(funC1, funC2)

注:resolve, reject 均可传参, 对应的下一步可以接受数据


new Promise(funA).then(funB).catch(funC)

funA 里执行方法 resolve 或 reject
结果正确执行 resolve() 走then(funB)
结果错误执行 reject() 走catch(funC)

new Promise(funA).then(funB, funC)

funA 里执行方法 resolve 或 reject
结果正确执行 resolve() 走then第一个参数 funB
结果错误执行 reject() 走then第二个参数 funC

new Promise(funA).then(funB).then(funC)

funA 里执行方法 resolve
funB 里返回一个 Promise
如果 funC 不区分 true, false 两种情况, funB 可以不返回 Promise, 只返回值也可以

function funB(input) {
	return new Promise(function(resolve, reject) {
		if(1) {
			resolve()
		} else {
			reject()
		}
	});
}

new Promise(funA).then(funB1, funB2).then(funC1, funC2)

相当于前面几种的结合应用



demo

<!DOCTYPE html>
<html>

	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta charset="utf-8">
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<title>Promise 4种常规用法</title>
		<style></style>
	</head>

	<body>

		<div>
			<div>new Promise(funA).then(funB).catch(funC)</div>
			<div>new Promise(funA).then(funB, funC)</div>
			<div>new Promise(funA).then(funB).then(funC)</div>
			<div>new Promise(funA).then(funB1, funB2).then(funC1, funC2)</div>
		</div>

		<script type="text/javascript">
			//new Promise(funA).then(funB).catch(funC)
			new Promise(function(resolve, reject) {
    
				if(Math.random() > 0.5)
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值