总结:
- 通过new Promise()
- 参数是一个回调函数, 回调函数中有两个参数 (resolve reject)
- resolve也是一个函数, 函数中接收参数, 参数为任务
- resolve 中任务主线程 , 而then中任务是放在异步队列中的,执行在主线程之后
- Promise对象的api
then(callback)
catch(cb) - all race
all([value1,value2])
指的是将数组中所有的任务执行完成之后, 才执行.then 中的任务
race表示赛跑, 谁快, 谁输出
项目中使用:
需求: 先获取数据,然后将获取的数据赋值给某一个变量
const p3 = new Promise((resolve,reject)=>{
request('http://api.douban.com/v2/movie/in_theaters',(err,res,data)=>{
resolve(data)
})
}).then((data)=>{
// console.log( data )
obj.data = data
}).then(()=>console.log(obj.data))
const request = require('request')
const obj = {
data: null
}
const p3 = new Promise((resolve,reject)=>{
request('http://api.douban.com/v2/movie/in_theaters',(err,res,data)=>{
resolve(data)
})
}).then((data)=>{
// console.log( data )
obj.data = data
}).then(()=>console.log(obj.data))
const p1 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(console.log('p1 任务1'))
},1000)
})
.then( data => {
console.log('p1 任务2')
})
.then( res => {
console.log('p1 任务3')
})
.catch( err =>{ throw err} )
const p2 = new Promise((resolve,reject)=>{
resolve(console.log('p2 任务1'))
}).then(
data => {
console.log('p2 任务2')
}
).catch(
err => {
throw err
}
)
// Promise.all([p1,p2])
// .then(()=>console.log('done'))
Promise.race([p1,p2])
.then(()=>{console.log('done~~')})