亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

關(guān)于Promise 異步編程的實(shí)例講解

 更新時(shí)間:2017年09月01日 08:49:49   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇關(guān)于Promise 異步編程的實(shí)例講解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

實(shí)例如下所示:

//1.解決異步回調(diào)問(wèn)題
//1.1 如何同步異步請(qǐng)求
//如果幾個(gè)異步操作之間并沒(méi)有前后順序之分,但需要等多個(gè)異步操作都完成后才能執(zhí)行后續(xù)的任務(wù),無(wú)法實(shí)現(xiàn)并行節(jié)約時(shí)間

const fs = require('fs');
let school = {};
fs.readFile('./name.txt','utf8',function (err,data) {
  school.name = data;
});
fs.readFile('./age.txt','utf8',function (err,data) {
  school.age = data;
});
console.log(school);
//1.2如何解決回調(diào)地獄
//在需要多個(gè)操作的時(shí)候,會(huì)導(dǎo)致多個(gè)回調(diào)函數(shù)嵌套,導(dǎo)致代碼不夠直觀,就是常說(shuō)的回調(diào)地獄

const fs = require('fs');
fs.readFile('./content.txt','utf8',function (err,data) {
  if(err)console.log(err);
  fs.readFile(data,'utf8',function (err,data) {
    if(err)console.log(err);
    console.log(data);
  })
});
//2.Promise
//Promise本意是承諾,在程序中的意思就是承諾我過(guò)一段時(shí)間后會(huì)給你一個(gè)結(jié)果。 什么時(shí)候會(huì)用到過(guò)一段時(shí)間?答案是異步操作,異步是指可能比較長(zhǎng)時(shí)間才有結(jié)果的才做,例如網(wǎng)絡(luò)請(qǐng)求、讀取本地文件等

//3.Promise的三種狀態(tài)
//例如媳婦說(shuō)想買個(gè)包,這時(shí)候他就要"等待"我的回復(fù),我可以過(guò)兩天買,如果買了表示"成功",如果我最后拒絕表示"失敗",當(dāng)然我也有可能一直拖一輩子

//Pending Promise對(duì)象實(shí)例創(chuàng)建時(shí)候的初始狀態(tài)
//Fulfilled 可以理解為成功的狀態(tài)
//Rejected 可以理解為失敗的狀態(tài)
//then 方法就是用來(lái)指定Promise 對(duì)象的狀態(tài)改變時(shí)確定執(zhí)行的操作,resolve 時(shí)執(zhí)行第一個(gè)函數(shù)(onFulfilled),reject 時(shí)執(zhí)行第二個(gè)函數(shù)(onRejected)
//4.構(gòu)造一個(gè)Promise
//4.1 promise的方法會(huì)立刻執(zhí)行
let promise = new Promise(()=>{
  console.log('hello');
});
console.log('world');
//4.2 promise也可以代表一個(gè)未來(lái)的值
const fs = require('fs');
let promise = new Promise((resolve,reject)=>{
  fs.readFile('./content.txt','utf8',function (err,data) {
    if(err)console.log(err);
    resolve(data);
  })
});
promise.then(data =>{
  console.log(data);
});
//4.3 代表一個(gè)用于不會(huì)返回的值
const fs = require('fs');
let promise = new Promise((resolve,reject)=>{});
promise.then(data =>{
  console.log(data);
});
//4.4 應(yīng)用狀態(tài)實(shí)現(xiàn)拋硬幣
function flip_coin() {
  return new Promise((resolve,reject)=>{
    setTimeout(function () {
      var random = Math.random();
      if(random > 0.5){
        resolve('正');
      }else{
        resolve('反');
      }
    },2000)
  })
}
flip_coin().then(data=>{
  console.log(data);
},data=>{
  console.log(data);
});
//5.實(shí)現(xiàn)簡(jiǎn)單的Promise
function Promise(fn) {
  fn((data)=>{
    this.resolve(data)

  },(data)=>{
    this.reject(data);
  })
}
Promise.prototype.resolve = function (data) {
  this._success(data)
};
Promise.prototype.reject = function (data) {
  this._error(data);
};
Promise.prototype.then = function (success,error) {
  this._success = success;
  this._error = error;
};
//6.Error會(huì)導(dǎo)致觸發(fā)Reject
//可以采用then的第二個(gè)參數(shù)捕獲失敗,也可以通過(guò)catch函數(shù)進(jìn)行捕獲

function flip_coin() {
  return new Promise((resolve,reject)=>{
    throw Error('沒(méi)有硬幣')
  })
}
flip_coin().then(data=>{
  console.log(data);
}).catch((e)=>{
  console.log(e);
})
//7.Promise.all實(shí)現(xiàn)并行
//接受一個(gè)數(shù)組,數(shù)組內(nèi)都是Promise實(shí)例,返回一個(gè)Promise實(shí)例,這個(gè)Promise實(shí)例的狀態(tài)轉(zhuǎn)移取決于參數(shù)的Promise實(shí)例的狀態(tài)變化。當(dāng)參數(shù)中所有的實(shí)例都處于resolve狀態(tài)時(shí),返回的Promise實(shí)例會(huì)變?yōu)閞esolve狀態(tài)。如果參數(shù)中任意一個(gè)實(shí)例處于reject狀態(tài),返回的Promise實(shí)例變?yōu)閞eject狀態(tài)

const fs = require('fs');
let p1 = new Promise((resolve,reject)=>{
  fs.readFile('./name.txt','utf8',function (err,data) {
    resolve(data);
  });
})
let p2 = new Promise((resolve,reject)=>{
  fs.redFile('./age.txt','utf8',function (err,data) {
    resolve(data);
  });
})
Promise.all([p1,p2]).then(([res1,res2])=>{
  console.log(res1);
})
//不管兩個(gè)promise誰(shuí)先完成,Promise.all 方法會(huì)按照數(shù)組里面的順序?qū)⒔Y(jié)果返回
//8.Promise.race實(shí)現(xiàn)選擇接受一個(gè)數(shù)組,數(shù)組內(nèi)都是Promise實(shí)例,返回一個(gè)Promise實(shí)例,這個(gè)Promise實(shí)例的狀態(tài)轉(zhuǎn)移取決于參數(shù)的Promise實(shí)例的狀態(tài)變化。當(dāng)參數(shù)中任何一個(gè)實(shí)例處于resolve狀態(tài)時(shí),返回的Promise實(shí)例會(huì)變?yōu)閞esolve狀態(tài)。如果參數(shù)中任意一個(gè)實(shí)例處于reject狀態(tài),返回的Promise實(shí)例變?yōu)閞eject狀態(tài)。

const fs = require('fs');
let p1 = new Promise((resolve,reject)=>{
  fs.readFile('./name.txt','utf8',function (err,data) {
    resolve(data);
  });
})
let p2 = new Promise((resolve,reject)=>{
  fs.readFile('./age.txt','utf8',function (err,data) {
    resolve(data);
  });
})
Promise.race([p1,p2]).then(([res1,res2])=>{
  console.log(res1,res2);
})
9.Promise.resolve
//返回一個(gè)Promise實(shí)例,這個(gè)實(shí)例處于resolve狀態(tài)。

Promise.resolve('成功').then(data=>{
  console.log(data);
})
10.Promise.reject
//返回一個(gè)Promise實(shí)例,這個(gè)實(shí)例處于reject狀態(tài)

Promise.reject('失敗').then(data=>{
  console.log(data);
},re=>{
  console.log(re);
})
//11.封裝ajax
function ajax({url=new Error('url必須提供'),method='GET',async=true,dataType='json'}){
 return new Promise(function(resolve,reject){
   var xhr = new XMLHttpRequest();
   xhr.open(method,url,async);
   xhr.responseType = dataType;
   xhr.onreadystatechange = function(){
     if(xhr.readyState == 4){
       if(/^2\d{2}/.test(xhr.status)){
        resolve(xhr.response);
       }else{
         reject(xhr.response);
       }
     }
   }
   xhr.send();
 });
}
//12.chain中返回結(jié)果
Promise.resolve([1,2,3])
.then(arr=>{
  return [...arr,4]
}).then(arr=>{
  return [...arr,5]
}).then(arr=>{
  console.log(arr);
})
//13.chain中返回promise
//then中的結(jié)果是promise的resolve后的結(jié)果

Promise.resolve('user').then(data=>{
  return new Promise(function (resolve,reject) {
    fetch('/'+data).then(res=>res.json().then((json)=>{
      resolve(json)
    }))
  })
}).then(data=>{
  console.log(data);
});
//改寫的更簡(jiǎn)單些

Promise.resolve('user').then(data=>{
  return fetch('/'+data)
}).then(res=>{
  return res.json();
}).then(data=>{
  console.log(data);
})
//14.async/await
//本質(zhì)是語(yǔ)法糖,await與async要連用,await后只能跟promise

async function getHello() {
  return new Promise((resolve,reject) => {
    setTimeout(function () {
      resolve('hello');
    },2000);
  })
}
async function getData () {
  var result = await getHello();
  console.log(result);
} ;
getData();

以上這篇基于Promise 異步編程的實(shí)例講解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論