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

相关推荐
小羊没烦恼!18 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
三十而立洋19 小时前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
伞伞悦读19 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
卡布鲁20 小时前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
C语言小火车20 小时前
C/C++ 为什么需要编译器?
开发语言·c++
李少兄20 小时前
JavaScript 隐式全局变量解析
javascript
霍霍的袁21 小时前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超1 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int1 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
沙蒿同学1 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端