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

相关推荐
布莱克60532 分钟前
Swift 类详解:从定义、继承到内存管理的完整指南
服务器·开发语言·ios·ssh·swift·类
是main不是漫1 小时前
【快慢指针 | LeetCode202 快乐数】鸽巢原理佐证环特性,快慢指针巧解快乐数
c语言·开发语言·c++·算法
布莱克6053 小时前
Swift 方法详解:实例方法、类型方法与 mutating 机制
服务器·开发语言·ios·ssh·swift·方法
Risehuxyc4 小时前
PHP能不能在参数里放匿名函数
开发语言·php
码云社区4 小时前
Java家政服务系统源码:人员技能、服务范围与多商家业务落地
java·开发语言·家政服务·家政小程序·家政系统
FRing035 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
whitelbwwww7 小时前
CUDA C++实战--中级
开发语言·前端·c++
FungLeo7 小时前
FengCMS · PHP+MySQL 升级实录 · 内容写入一致性:锁等待超时与跨模型子树删除竞态
开发语言·mysql·php·工程实践·fengcms
inksci7 小时前
用飞帆做了个小网页
前端·javascript·css·html
zhensherlock8 小时前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js