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

相关推荐
harrain16 小时前
什么!vue3.4开始,v-model不能用在prop上
前端·javascript·vue.js
阿蒙Amon21 小时前
TypeScript学习-第7章:泛型(Generic)
javascript·学习·typescript
睡美人的小仙女12721 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
fanruitian21 小时前
uniapp android开发 测试板本与发行版本
前端·javascript·uni-app
rayufo1 天前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk1 天前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
摘星编程1 天前
React Native + OpenHarmony:Timeline垂直时间轴
javascript·react native·react.js
缺点内向1 天前
C#编程实战:如何为Word文档添加背景色或背景图片
开发语言·c#·自动化·word·.net
一起养小猫1 天前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
zhougl9961 天前
Java 所有关键字及规范分类
java·开发语言