javascript Promise
Promise对象构造时需要一个参数,这个参数必须是一个函数。
1 | |
当一个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
15function 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出来的)