【JS】JavaScript Promise

代码举例

javascript 复制代码
	function test(resolve, reject) {
		let timeOut = Math.random() * 2;
		console.log("11")
		
		setTimeout(function() {
			if(timeOut < 1) {
				console.log("ok", timeOut)
				resolve("ok " + timeOut);
			}else {
				console.log("timeOut", timeOut)
				reject("error " + timeOut);
			}
		}, timeOut * 1000);
		console.log("22")
	}
	
	console.log("1");
	
	//方式1
	new Promise(test).then(result => {
		console.log("ok", result);
	}).catch(result => {
		console.log("error", result);
	})
	
	console.log("2");

方式1

javascript 复制代码
	new Promise(test).then(result => {
		console.log("ok", result);
	}).catch(result => {
		console.log("error", result);
	})

方式2

javascript 复制代码
	new Promise(test).then(
		(result) => {
			console.log("ok", result);
		},
		(error) => {
			console.log("error", error);
		}
	)

执行结果

注意

then, catch, finally 顺序不能颠倒。

相关推荐
AOwhisky17 分钟前
Python 学习笔记(第五期)——组合数据类型:列表、元组、集合与字典精讲——核心知识点自测与详解
开发语言·笔记·python·学习·云计算
To_OC8 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
灯澜忆梦9 小时前
GO_并发编程---定时器
开发语言·后端·golang
-银雾鸢尾-10 小时前
C#中的StringBuilder相关方法
开发语言·c#
To_OC10 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn10 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
-银雾鸢尾-10 小时前
C#中结构体与类的区别;抽象类与接口的区别
开发语言·c#
এ慕ོ冬℘゜11 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
大模型码小白11 小时前
【Python零基础教程】继承、多态与魔法函数:面向对象编程三大核心特性详解
java·大数据·开发语言·人工智能·python·ai编程
随心点儿11 小时前
js postMessage 实现跨域发送消息-应用示例
javascript·ecmascript·postmessage