Powerful promise

This stuff is called Prometheus, stealing fire hero of Greek mythology
promise only used to wrap asynchronous function, synchronization will mess up the order of execution, production BUG

// 如何使用
function pro(){  
   return new Promise(function(resolve,reject){
      setTimeout(function(){
          var num = parInt(Math.random()*10);
          if(num>5){ 
             resolve(num) 
             // 这个可以写成
             // return  Promise.resolve(num)
          }else{ 
             reject(num) 
             // 这个可以写成
             // return  Promise.reject(num)
          } 
      },5000)
   })
}
// pro()这个返回的是一个pending的Promise对象
// Promise可以被then启动,参数有两个,跟new的时候对应也是两个
// new的时候第一个参数传递成功,then的时候第一个参数接受成功
// new的时候第二个参数传递失败,then的时候第二个参数接受失败
pro().then((res)=>{ ... },(error)=>{ ... })

The wording of the api is fixed, asynchronous callback function used to turn into a chain of asynchronous function
check conventional asynchronous callback function

function ajax1(){
   ajax({
       sucess:function(res1){
           //回调ajax2,或者直接把第二个ajax写在这里面
           ajax2(res1)
       }
   })
}
function ajax2(res1){
   ajax({
       sucess:function(res2){
           ...
       }
   })
}
ajax1()

Promise wording

function ajax1(){  
   return new Promise((resolve,reject)=>{
      ajax({
         sucess:function(res1){
           //回调ajax2,或者直接把第二个ajax写在这里面
           resolve(res1)
         }
      })
   }
}
function ajax2(){  
   return new Promise((resolve,reject)=>{
      ajax({
         sucess:function(res2){
           //回调ajax2,或者直接把第二个ajax写在这里面
           resolve(res2)
         }
      })
   }
}
ajax1().then((res1)=>{
   return ajax2(res1)
}).then((res2)=>{
   ...
})

promise.resolve

let res = Promise.resolve("123")
res.then(res=>{ console.log(res) })

promise.reject

let res = Promise.reject("123")
res.then(res=>{ console.log(res) })

Promise.all
this in several cases need to request but asynchronous functions not related to each other
often used as an initialization loaded using

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
},(error)=> {
  console.log(error)
});
// 如果上面几个promise函数没有全部返回成功,就会指向error

Read the above wording feel much better than this right, there is no change, the code also changed much, I also think so, until you see async use with Promise

async
this is syntactic sugar Generator function of
what is syntactic sugar, is easier to use, the second package
What is Generator function, this is the api es6, no one knew was that he was syntactic sugar async to grab the headlines, so no matter, you know how to use async syntactic sugar on the line

Any function can be added in front of the word asyncupgrade function to manage asynchronous function
async only be used in the scope of the function, if the function is a function of where you have to write again the async
async await keep up with the use of, or no raison d'etre
await a promise to connect function, primise If an asynchronous function of
these points does not comply with the order of execution, and so there must be some of the BUG

function ajax1(){  
   return new Promise((resolve,reject)=>{
      ajax({
         sucess:function(res1){
           //回调ajax2,或者直接把第二个ajax写在这里面
           resolve(res1)
         }
      })
   }
}
function ajax2(opt){  
   return new Promise((resolve,reject)=>{
      ajax({
         sucess:function(res2){
           //回调ajax2,或者直接把第二个ajax写在这里面
           resolve(res2)
         }
      })
   }
}
async function init(){
   var res1 = await ajax1()
   var opt = res1 + 1; //模拟正常的方法什么的
   var res2 = await ajax2(opt)
}
init() 

If the above code is the synchronization code we are well understood, but because it is asynchronous, it is difficult to understand, and it is normal because ajax1 and ajax2 is asynchronous, res1 and res2 will only get undefined, this running order the peak of the fundamental understanding of asynchronous, are you sure this is no problem code execution down?
There is no problem you can try yourself

async Error Handling

// 统一处理
async function init(){
   try{
      var aa = await A()
      var bb = await B()
   }catch(err) {
      console.log(err)  
   }
}

// 单独处理
async function init(){
   const [err, data] = await A().then(data => [null, data]).catch(err => [err, null])
   const [err, data] = await B().then(data => [null, data]).catch(err => [err, null])
}

// 上面的优化写法
// 抽离成公共方法
const awaitWrap = (promise) => {
  return promise
   .then(data => [null, data])
   .catch(err => [err, null])
}
async function init(){
   const [err, data] = await awaitWrap(A())
   const [err, data] = await awaitWrap(B())
}

How to understand the async do
we believe await blocked thread, if there is to find out about java, there is a method in the java yeild, this method is syntactic sugar await. This API allows asynchronous turned into a synchronous, make the code more easy to understand

Do a network speed
network speed on the premise that large server bandwidth
principle is to allow recursive front-end server to get a picture for download network speed, then turn base64 recursive upload pictures get uploaded network speed, I made five experiments

First

var index = 10;
function yi() {
    var start = new Date().getTime()
    var img = document.createElement("img");
    var num = Math.random()
    img.src = './img/xxx.png?num=' + num;
    img.onload = function (res){
        var end = new Date().getTime()
        console.log("递归----"+(end-start))
        index--;
        if(index!=0){
            yi()
        }
    }
}
yi()

the second

var index = 10;
var promiseArr = [];
function getImg() {
return new Promise(function (resolve, reject) {
    var start = new Date().getTime()
    var img = document.createElement("img");
    var num = Math.random()
    img.src = './img/girs.png?num=' + num;
    img.onload = function (res){
    var end = new Date().getTime()
    console.log("Promise.all----"+(end-start))
    resolve(end-start);
    }
})
}
function er() {
   for(var i=0;i<10;i++){
     promiseArr.push(getImg())
   }
   Promise.all(promiseArr).then()
}
er()

The third

function getImg() {
   return new Promise(function (resolve, reject) {
    var start = new Date().getTime()
    var img = document.createElement("img");
    var num = Math.random()
    img.src = './img/girs.png?num=' + num;
    img.onload = function (res){
        var end = new Date().getTime()
        console.log("10次await-----"+(end-start))
        resolve(end-start);
    }
   })
}
async function san() {
   var allTime = 0;
   allTime += await getImg();
   allTime += await getImg();
   allTime += await getImg();
   allTime += await getImg();
   allTime += await getImg();
   allTime += await getImg();
   allTime += await getImg();
   allTime += await getImg();
   allTime += await getImg();
   allTime += await getImg();
}
san()

the fourth

function getImg() {
   return new Promise(function (resolve, reject) {
    var start = new Date().getTime()
    var img = document.createElement("img");
    var num = Math.random()
    img.src = './img/girs.png?num=' + num;
    img.onload = function (res){
        var end = new Date().getTime()
        console.log("for(x){await x}-----"+(end-start))
        resolve(end-start);
    }
   })
}
async function si() {
   var arr = []
   for(var i=0;i<10;i++){
    arr.push(getImg())
   }   
   for (const x of arr){
    await x;
   }
}
si()

the fifth

function getImg() {
   return new Promise(function (resolve, reject) {
    var start = new Date().getTime()
    var img = document.createElement("img");
    var num = Math.random()
    img.src = './img/girs.png?num=' + num;
    img.onload = function (res){
        var end = new Date().getTime()
        console.log("for await(x){x}+-----"+(end-start))
        resolve(end-start);
    }
   })
}
async function wu() {
   var arr = []
   for (var i=0;i<10;i++){
    arr.push(getImg())
   }
   for await(const x of arr){
    x;
   }
}
wu()

The execution time of the five codes are not the same, why have studies

A version of the package promise ajax

function ajax(url, method = 'get', param = {}) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        const paramString = getStringParam(param);
        if (method === 'get' && paramString) {
            url.indexOf('?') > -1 ? url += paramString : url += `?${paramString}`
        }
        xhr.open(method, url);
        xhr.onload = function () {
            const result = {
                status: xhr.status,
                statusText: xhr.statusText,
                headers: xhr.getAllResponseHeaders(),
                data: xhr.response || xhr.responseText
            }
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                resolve(result);
            } else {
                reject(result);
            }
        }
        // 设置请求头
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        // 跨域携带cookie
        xhr.withCredentials = true;
        // 错误处理
        xhr.onerror = function () {
            reject(new TypeError('请求出错'));
        }
        xhr.timeout = function () {
            reject(new TypeError('请求超时'));
        }
        xhr.onabort = function () {
            reject(new TypeError('请求被终止'));
        }
        if (method === 'post') {
            xhr.send(paramString);
        } else {
            xhr.send();
        }
    })
}

function getStringParam(param) {
    let dataString = '';
    for (const key in param) {
        dataString += `${key}=${param[key]}&`
    }
    return dataString;
}

Guess you like

Origin www.cnblogs.com/pengdt/p/12037983.html