/*
? ? promise 承諾
? ? ? es6中的語法
? ? ? 當(dāng)你要執(zhí)行異步代碼的時候
? ? ? 給我,我會給你一個結(jié)果
? ? Promise 也是js中內(nèi)置的構(gòu)造函數(shù),Promise可以實例化對象
? ? // new 構(gòu)造函數(shù)的時候,傳遞一個參數(shù),參數(shù)是一個回調(diào)函數(shù)
? ? // 在執(zhí)行 new 構(gòu)造函數(shù)的時候,就會執(zhí)行這個回調(diào)函數(shù)
? ? 語法:
? ? let p = new Promise(function(resolve,reject){
? ? ? // 此處執(zhí)行異步代碼
? ? })
? ? p 就是promise對象
? ? promise對象有then 和 catch 方法
? ? ? 當(dāng)異步代碼成功的時候,也就是resolve調(diào)用的時候,會執(zhí)行promise的then方法
? ? ? ? resolve(參數(shù)1)? .then(function(形參1){})
? ? ? ? resolve調(diào)用的時候參數(shù)1 會傳遞給形參1
? ? ? 當(dāng)異步代碼失敗的時候,也就是reject調(diào)用的時候,會執(zhí)行promise的catch方法
? ? 異步代碼的執(zhí)行狀態(tài):也就是promise對象的狀態(tài)
? ? ? pending? 執(zhí)行中
? ? ? resolved(fulfilled) 成功
? ? ? rejected? 失敗
? ? promise的狀態(tài)變化,只能從 `執(zhí)行中` 到? `成功`,或者 `執(zhí)行中` 到 `失敗`
? */
? // let p = new Promise((resolve,reject)=>{
? //? // console.log('實例化promise對象的時候就執(zhí)行');
? //? // 這個函數(shù)有兩個參數(shù),也是回調(diào)函數(shù)
? //? // 當(dāng)異步代碼執(zhí)行成功的時候,調(diào)用res函數(shù),
? //? // 當(dāng)異步代碼執(zhí)行失敗的時候,調(diào)用rej函數(shù)
? //? resolve('hello');
? //? // reject(00);
? //? // console.log('此代碼有執(zhí)行,但是promise狀態(tài)不改變');
? // })
? // console.log(p);
? // p.then(function(str){
? //? console.log(str); // hello
? //? console.log('我們完成啦');
? // }).catch(function(num){
? //? console.log(num);
? // })
? // then可以連寫,但是后面的then方法中的回調(diào)函數(shù)獲取不到參數(shù)
? // p.then(num=>console.log(num)).then(num2=>{
? //? console.log(num2);
? //? console.log(12345);
? // })
? // promise的鏈?zhǔn)秸{(diào)用
? // 當(dāng)then方法中回調(diào)函數(shù)返回的是一個新的promise對象,則后面的then方法,只有在這個新promise對象中調(diào)用resolve函數(shù)才執(zhí)行
? new Promise((reslove,reject)=>{
? ? reslove('12345');
? })
? .then(function(str){
? ? console.log(str);
? ? return new Promise(function(resolve,reject){
? ? ? resolve(str)
? ? })
? })
? .then(function(num){
? ? console.log(num);
? })
/*
? ? async/await
? ? 異步 / 等待
? ? async這個關(guān)鍵字是用來修飾函數(shù)的
? ? ? 被async修飾的函數(shù),里面的可以使用await關(guān)鍵字
? ? ? await 用來修飾異步的promise的,可以讓異步代碼,在函數(shù)中以同步代碼的形式執(zhí)行
? */
? // async 修飾函數(shù)
? async function fn(){
? ? // 使用pAjax請求04-await.php
? ? // await 修飾的代碼,會當(dāng)做同步代碼執(zhí)行,如果當(dāng)前代碼沒有執(zhí)行結(jié)束,則后面的代碼也不會執(zhí)行
? ? // 通過await修飾后的異步代碼,可以當(dāng)做同步代碼一樣接受返回值
? ? let result = await pAjax({
? ? ? url: './04-await.php',
? ? ? fn:(res)=>{
? ? ? ? // console.log(res);
? ? ? ? resolve(res)
? ? ? }? ?
? ? }).then(num=>{
? ? ? // console.log(num);
? ? ? return num
? ? })
? ? // 接收到pAjax請求的返回值
? ? console.log(result);
? ? console.log('666');
? }
? fn();