【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 顺序不能颠倒。

相关推荐
Dxy12393102167 分钟前
JS DES 加密详解
开发语言·javascript·arcgis
充值内卷7 分钟前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++
云和数据.ChenGuang20 分钟前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
nice_lcj5201 小时前
深入理解 Java 反射:从 Class 对象到方法调用(含性能实测 + 迷你 IOC 实战 + 面试考点)
java·开发语言·后端·面试
椒哥3 小时前
一天被问几十次"允许",我统计了 517 次,然后写了个插件
前端·javascript·github
樱花树下的数学喵3 小时前
手写简易 STL string|C++ 字符串底层实现
开发语言·c++
kyriewen3 小时前
我测了 6 种防请求竞态的写法:只有 1 种真能打
前端·javascript·程序员
jimy13 小时前
C++ 报错的 qualifiers 的意思
开发语言·c++
OpsEye4 小时前
企业大模型压测,需要重点关注哪些指标?
javascript·ai编程
像我这样帅的人丶你还5 小时前
我html生成的doc文档为何在手机文档显示不了图片?
前端·javascript