javascript Promise

Promise对象构造时需要一个参数,这个参数必须是一个函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let prom = new Promise(function (resolve, reject) {
console.log("Run");
// 进行费时间的异步操作
...
//

if(success) {
resolve(res_you_want_return)
} else {
reject(error_msg)
}
}).then(function(res_i_want_to_get_when_success){
console.log('OK')
console.log(res_i_want_to_get_when_success)
// 这里的 res_i_want_to_get_when_success 就是 res_you_want_return
}).catch(function(error_msg){
console.error(error_msg)
// 这里的error_msg就是上面的error_msg
});

当一个Promise对象被构造时,立即 在另外的线程中异步执行传入构造函数的函数。

在执行的同时,then方法也被执行,then的作用是在“成功回调列表”中添加一个函数,catch则是在“失败回调列表”中添加一个回调函数。添加回调函数并不意味着要执行回调函数,所以then/catch方法是即时结束的,不会阻塞主线程。等到resolve或者reject被执行后,再依次执行回调列表中的函数。

如何获取promise resolve后的原始数据?

promise resolve后会返回一个Promise对象,这个对象包含了原始数据,但是如何获取原始数据类型呢?

对于网络请求,再json()方法返回后,多用一次then方法即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function djc(params) {
js = params.json()
js.then(
pa => console.log(typeof pa)
)
}

fetch("https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo?room_id=22575741&protocol=0,1&format=0,1,2&codec=0,1&qn=10000&platform=web&ptype=8&dolby=5&panorama=1", {
"referrer": "https://live.bilibili.com/22575741",
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
}).then(djc);

参见:https://blog.csdn.net/M_H5211/article/details/116160429

另外,同一个promise多次then,下一次用上一次的return值,不会被Promise包装,但是第一个then,收到的会是包含结果的Promise对象(因为是被resolve出来的)


javascript Promise
https://horizon86.github.io/2022/12/12/javascript Promise/
作者
horizon86
发布于
2022年12月12日
许可协议