做茶葉網(wǎng)站哪些平臺可以發(fā)廣告
一、async函數(shù)
async是一個加在函數(shù)前的修飾符,被async定義的函數(shù)會默認返回一個Promise對象resolve的值。
因此對async函數(shù)可以直接then,返回值就是then方法傳入的函數(shù)。
// async基礎(chǔ)語法
async function fun0(){console.log(1);return 1;
}
fun0().then(val=>{console.log(val) // 1,1
})async function fun1(){console.log('Promise');return new Promise(function(resolve,reject){resolve('Promise')})
}
fun1().then(val => {console.log(val); // Promise Promise
}
//聲明一個async函數(shù)
async function main() {console.log('async function');//情況1:返回非promise對象數(shù)據(jù)return 'hahaha';//情況2:返回是promise對象數(shù)據(jù)/* return new Promise((resolve, reject) => {// resolve('ok');reject('error');}) *///情況3:拋出異常// throw new Error('出錯啦!!!');
}
let result = main().then(value => {console.log(value);
});
console.log(result);
二、await表達式
await 也是一個修飾符,只能放在async定義的函數(shù)內(nèi)。可以理解為等待。
await 修飾的如果是Promise對象,可以獲取Promise中返回的內(nèi)容(resolve或reject的參數(shù)),且取到值后語
句才會往下執(zhí)行;如果不是Promise對象:把這個非promise的東西當做await表達式的結(jié)果。
注意事項
- await必須寫在async函數(shù)中,但是async函數(shù)中可以沒有await
- 如果await的promise失敗了,就會拋出異常,需要通過try…catch捕獲處理
async function fun(){let a = await 1;let b = await new Promise((resolve,reject)=>{setTimeout(function(){resolve('setTimeout')},3000)})let c = await function(){return 'function'}()console.log(a,b,c)
}
fun(); // 3秒后輸出: 1 "setTimeout" "function"
function log(time){setTimeout(function(){console.log(time);return 1;},time)
}
async function fun(){let a = await log(1000);let b = await log(3000);let c = log(2000);console.log(a);console.log(1)
}
fun();
// 立即輸出 undefined 1
// 1秒后輸出 1000
// 2秒后輸出 2000
// 3秒后輸出 3000
async function main() {//1、如果await右側(cè)為非promise類型數(shù)據(jù)var rs = await 10;var rs = await 1 + 1;var rs = await "非常6+7";//2、如果await右側(cè)為promise成功類型數(shù)據(jù)var rs = await new Promise((resolve, reject) => {resolve('success');})//3、如果await右側(cè)為promise失敗類型數(shù)據(jù),需要借助于try...catch捕獲try {var rs = await new Promise((resolve, reject) => {reject('error');})} catch (e) {console.log(e);}
}
main();
// 使用async/await獲取成功的結(jié)果// 定義一個異步函數(shù),3秒后才能獲取到值(類似操作數(shù)據(jù)庫)
function getSomeThing(){return new Promise((resolve,reject)=>{setTimeout(()=>{resolve('獲取成功')},3000)})
}async function test(){let a = await getSomeThing();console.log(a)
}
test(); // 3秒后輸出:獲取成功
案例:async結(jié)合await讀取文件內(nèi)容
//1、導(dǎo)包
const fs = require('fs');
const {promisify} = require('util');
//2、將fs.readFile轉(zhuǎn)化成promise風格的函數(shù)
const myreadfile = promisify(fs.readFile);
//3、聲明async函數(shù)
async function main(){try{//4、讀取文件let one = await myreadfile('./resource/4.html');let two = await myreadfile('./resource/2.html');let three = await myreadfile('./resource/3.html');//5、拼接讀取文件內(nèi)容console.log(one + two + three);}catch(e){console.log(e);}
}
//6、調(diào)用main函數(shù)
main();