简单回答: 一种异步的解决方案

回顾一下什么是异步
事件 / setTimeout
异步执行的时机
同步->异步微任务->GUI渲染->异步宏任务
传统的异步解决方案: 回调
回调: 顾名思义 回头调用
- function a (fn:函数){
- if(成功){
- fn()
- }
- }
- a(function(){})
智力小测验:
- //如何实现如下代码
- getRes(1)(2)(3)(4)//结果 1+2+3+4 = 10
回调地狱
- doSomething(function (result) { //第一个函数function就是sucessCallback
- doSomethingElse(result, function (newResult) {
- doThirdThing(newResult, function (finalResult) {
- console.log('Got the final result' + finalResult)
- }, failureCallback)
- }, failureCallback)
- }, failureCallback)
- //创造一个Promise实例
- const promise = new Promise(function(resolve, reject) {
- // ... some code
-
- if (/* 异步操作成功 */){
- resolve(value);
- } else {
- reject(error);
- }
- });
-
- //上述代码可改进为:
- doSomething().then(function(result) { //result是doSomething函数成功执行的返回值
- return doSomethingElse(result) //执行器函数,同步回调
- })
- .then(function(newResult){ //newResult是doSomethingElse成功执行的返回值
- return doThirdThing(newResult)
- })
- .then(function(finalResult){
- console.log('Got the final result' + finalResult)
- })
- .catch(failureCallback) //统一的错误处理
根本上去掉回调 await一般结合promise使用
- async function request() {
- try{
- const result = await doSomething()
- const newResult = await doSomethingElse(result)
- const finalResult = await doThirdThing(newResult)
- console.log('Got the final result' + finalResult)
- } catch (error) {
- failureCallback(error)
- }
- }
课堂练习
- //如何得到结果 打印--->随便什么数据1
- function runAsync1(){
- var p = new Promise(function(resolve, reject){
- //做一些异步操作
- setTimeout(function(){
- console.log('异步任务1执行完成');
- resolve('随便什么数据1');
- }, 1000);
- });
- return p;
- }
- function loadImageAsync(url) {
- return new Promise(function(resolve, reject) {
- const image = new Image();
- image.onload = function() {
- resolve(image);
- };
- image.onerror = function() {
- reject(new Error('Could not load image at ' + url));
- };
- image.src = url;
- });
- }
- //函数调用
- loadImageAsync('7.png').then((image)=>{
- console.log(image)
- },(e)=>{
- console.log(e)
- })
扩展
- //all 全部执行 按顺序
- Promise
- .all([runAsync1(), runAsync2(), runAsync3()])
- .then(function(results){
- console.log(results);
- });
- //race 全部执行 谁快谁先
- Promise
- .race([runAsync1(), runAsync2(), runAsync3()])
- .then(function(results){
- console.log(results);
- });
总结:
promise:
- 1. 解决了回调地狱问题 取而代之的是用链式调用 把执行和结果处理分2块
- 2. 解决异步性能等待的性能问题
- 3. 易读性更高,代码更加优雅,风格更加风骚