Promise basis of learning

promise

1. promise is what to do?

  1. Mainly used for asynchronous computation
  2. It may be queued asynchronous operation, performed in a desired order, returning a result in line with expectations
  3. Can be passed between objects and operations promise to help us process queue

2. Why should promise

Processing asynchronous operation

Asynchronous: Working sucked takes a long time after the delivery of the A to the system, go to continue to do work B delivered. Wait until the system completes the front of the work, and then through the callback or an event, A to continue to do the rest. Order to complete the work of AB, and deliver their chronological nothing to do, so called "asynchronous."

3. The common syntax asynchronous operation

  1. Event Listeners
document.getElementById('#start').addEventListener('click', start, false);
function start() {
  // 响应事件,进行相应的操作
}
// jquery on 监听
$('#start').on('click', start)
  1. Callback
// 比较常见的有ajax
$.ajax('http://www.wyunfei.com/', {
 success (res) {
   // 这里可以监听res返回的数据做回调逻辑的处理
 }
})

// 或者在页面加载完毕后回调
$(function() {
 // 页面结构加载完成,做回调逻辑处理
})
  1. Asynchronous callback problem
  • Before asynchronous processing is handled by the form of pure callback function
  • It is easy to enter the callback hell, deprived of the ability to function return
  • The problem can be solved, but it is difficult to read and difficult to maintain
  • The slightest mistake will step into the callback Hell - nested levels deep, bad maintenance

4. promise of appearance

  • promise is an object, the difference between the object and functions that can save the state of the object, the function can not (except closure)
  • Deprived of the ability to function does not return, so no transfer layers callback, call back to get data
  • Coding style, easy to understand, easy to maintain
  • Waiting for a plurality of asynchronous combined facilitate the solution

5. promise Detailed

new Promise(
  function (resolve, reject) {
    // 一段耗时的异步操作
    resolve('成功') // 数据处理完成
    // reject('失败') // 数据处理出错
  }
).then(
  (res) => {console.log(res)},  // 成功
  (err) => {console.log(err)} // 失败
)
  • role is to resolve the state of the object from Promise "unfinished" to "success" (i.e., changed from pending resolved), upon successful call asynchronous operation, and the result of the asynchronous operation, to pass out as a parameter
  • role is to eject the object from the state Promise "unfinished" to "failed" (i.e., changed from pending Rejected), invoked when an asynchronous operation fails, and the asynchronous operation errors may be, as a parameter to pass out
  • There are three states promise
  1. pending [Pending] original state
  2. fulfilled [realize] successful operation
  3. Rejected [rejected] operation failed
  • When the status changes promise, it will trigger the then () function in response to the subsequent steps of
  • a promise altered state, will not change
  • Promise object changes state, only two possibilities:
    • From pending becomes fulfilled
    • From pending changes to rejected

Example:

new Promise(resolve => {
  setTimeout(() => {
    resolve('hello')
  }, 2000)
}).then(res => {
  console.log(res)
})

Perform twice:

new Promise(resolve => {
    setTimeout(() => {
      resolve('hello')
    }, 2000)
  }).then(val => {
    console.log(val) //  参数val = 'hello'
    return new Promise(resolve => {
      setTimeout(() => {
        resolve('world')
      }, 2000)
    })
  }).then(val => {
    console.log(val) // 参数val = 'world'
  })

After the promise then:

let pro = new Promise(resolve => {
   setTimeout(() => {
     resolve('hello world')
   }, 2000)
 })
 setTimeout(() => {
   pro.then(value => {
   console.log(value) // hello world
 })
 }, 2000)

After the promise as the most important feature of the queue, we generated a promise queue at any one place, we can put him as a variable passed to other places.

6. then()

  1. Receiving as a function of two parameters representing Fulfilled (success) and Rejected (failure)
  2. then () returns a new instance of Promise, so it can be chained calls
  3. The current state of the surface change when Promise, .then () according to its final state, select a specific function execution status response
  4. State response function can return a new promise, or other value, return value can not we consider it returns a null;
  5. If the return of new promise, then the next level .then () will be executed after a new promise to change state
  6. If it returns any other value, then an .then (immediate execution)

7. .then () inside .then () in the case of

  1. Because .then () returns a Promise or examples
  2. Inside will wait then () executed, and then execution outside
new Promise(resolve=>{
			console.log('step 1')
			setTimeout(()=>{
				resolve(100)
			},1000)
		}).then((value)=>{
			return new Promise(resolve => {
				console.log('step 2')
				setTimeout(()=>{
					resolve(200)
				},1000)
			})
		}).then((value) => {
			console.log('step 3')
			return value
		}).then((value) => {
			console.log('step 4')
			return value
		}).then((value) => {
			console.log('step 5')
			console.log(value)
		})

8. Error Handling

Promise automatically captures internal abnormalities, and rejected response function to process
the first:

new Promise(resolve=>{
			setTimeout(()=>{
				throw new Error('bye')
			},1000)
		}).then(val=>{
			console.log(val)
		}).catch(err => {
			console.log('error',error)
		})
    //Uncaught Error: bye at 01.html:36

//第二种
new Promise(function(resolve, reject) {
			setTimeout(() => {
				reject('bye')
			}, 1000)
		}).then(()=>{
			console.log(val)
		},(err)=>{
			console.log('error:'+err)
		})
		//error:bye
  • Error handling two approaches
    • The first: reject ( 'error') .then (() => {}, () => {} error handling logic)
    • The second: throw new Error ( 'error') .catch (() => {} error handling logic)
    • Recommend use the second approach, more clear easy to read, and can capture all the previous error (can catch the N then error correction)

9. Promise.all () batch execution

  • Promise.all ([p1, p2, p3]) for a plurality of instances promise, Promise packaged into a new instance, the instance is returned ordinary promise
  • It receives an array as a parameter
  • Promise array can be an object, can be other than, wait for the status change will only Promise
  • When all the sub-Promise are completed, the Promise is completed, the return value is worth all the array
  • Any of a failure, the Promise fails, the return value is a failure of the first sub Promise Results
//切菜
		function cutUp() {
			console.log('开始切菜')
			var p=new Promise(function(resolve, reject) {
				setTimeout(() => {
					console.log('切菜完毕')
					resolve('切好的菜')
				}, 1000);
			})
			return p
		}
		//烧水
		function boil(params) {
			console.log('开始烧水')
			var p=new Promise(function(resolve, reject) {
				setTimeout(() => {
					console.log('烧水完毕')
					resolve('烧好的水')
				}, 1000);
			})
			return p
		}
		//汇总,切好菜 烧好水才做下一步
		Promise.all([cutUp(),boil()])
		.then(results => {
			console.log('准备工作完毕')
			console.log(results)
		})
		//开始切菜
		//开始烧水
		//切菜完毕
		//烧水完毕
		//准备工作完毕
		// ["切好的菜", "烧好的水"]

10. Promise.race()

Similar Promise.all (), except that it has a complete arbitrary even completed

let p1=new Promise(resolve=>{
		setTimeout(()=>{
			resolve('p1')
		},1000)
	})
	let p2=new Promise(resolve=>{
		setTimeout(()=>{
			resolve('p2')
		},500)
	})
	
	Promise.race([p1,p2]).then(value=>{
		console.log(value);//p2
	})

Combat:

/***
   第一步:找到北京的id
   第二步:根据北京的id -> 找到北京公司的id
   第三步:根据北京公司的id -> 找到北京公司的详情
   目的:模拟链式调用、回调地狱
 ***/
		//请求第一个API: 地址在北京的公司的id
		$.ajax({
			url: 'https://www.easy-mock.com/mock/5a52256ad408383e0e3868d7/lagou/city',
			success(resCity) {
				let findCityId = resCity.filter(item => {
					if (item.id = 'c1') {
						return item
					}
				})[0].id
				//  请求第二个API: 根据上一个返回的在北京公司的id “findCityId”,找到北京公司的第一家公司的id
				$.ajax({
					url: 'https://www.easy-mock.com/mock/5a52256ad408383e0e3868d7/lagou/position-list',
					success(resPosition) {
						let findPostionId = resPosition.filter(item => {
							if (findPostionId == item.id) {
								return item
							}
						})[0].id

						// 请求第三个API: 根据上一个API的id(findPostionId)找到具体公司,然后返回公司详情
						$.ajax({
							url: 'https://www.easy-mock.com/mock/5a52256ad408383e0e3868d7/lagou/company',
							success(resCom) {
								let comInfo = resCom.filter(item => {
									if (findPostionId == item.id) {
										return item
									}
								})[0]
								console.log(comInfo)
							}
						})
					}
				})
			}
		})




		//promise写法
		//第一步获取城市列表
		const cityList = new Promise((reslove, reject) => {
			$.ajax({
				url: 'https://www.easy-mock.com/mock/5a52256ad408383e0e3868d7/lagou/city',
				success(res) {
					reslove(res)
				}
			})
		})


		//第二步 找到城市是北京的id
		cityList.then(res => {
			let findCityId = res.filter(item => {
				if (item.id == 'c1') {
					return item
				}
			})[0].id
		})

		// 第四步(2):传入公司的id
		companyInfo(findPostionId)

		// 第三步(1):根据北京的id -> 找到北京公司的id
		function findCompanyId() {
			let aaa = new Promise((resolve, reject) => {
				$.ajax({
					url: 'https://www.easy-mock.com/mock/5a52256ad408383e0e3868d7/lagou/position-list',
					success(res) {
						resolve(res)
					}
				})
			})
			return aaa
		}

		findCompanyId().then(res => {
			// 第三步(2):根据北京的id -> 找到北京公司的id
			let findPostionId = res.filter(item => {
				if (item.cityId == findCityId) {
					return item
				}
			})[0].id



			// 第四步:根据上一个API的id(findPostionId)找到具体公司,然后返回公司详情
			function companyInfo(id) {
				let companyList = new Promise((resolve, reject) => {
					$.ajax({
						url: 'https://www.easy-mock.com/mock/5a52256ad408383e0e3868d7/lagou/company',
						success(res) {
							let comInfo = res.filter(item => {
								if (id == item.id) {
									return item
								}
							})[0]
							console.log(comInfo)
						}
					})
				})
			}
Published 21 original articles · won praise 0 · Views 278

Guess you like

Origin blog.csdn.net/my466879168/article/details/104849728