天天看點

promise與async、await

promise與async、await

promise用法

  1. promise基本用法
let p1 = new Promise((resolve, reject) => {
	setTimeout(() => {
		resolve('p1-ok');
	}, 1000);
});

let p2 = Promise.resolve('p2-ok');

p1.then((res) => {
	console.log(res);// p1-ok
	return p2;
}).then((res) => {
	console.log(res);// p2-ok
	// ...
});
           
  1. Promise.all(Array[Promise] array, Function callback)

    隻有當數組裡所有的promise執行個體執行成功,才會變為成功狀态,成功回調函數的參數是所有傳入的promise的傳回值組成的數組

let p1 = new Promise((resolve, reject) => {
	setTimeout(() => {
		resolve('p1-ok');
	}, 1000);
});

let p2 = Promise.resolve('p2-ok');

let p3 = Promise.reject(new Error('出錯了!'));

let pAll = Promise.all([p1, p2, p3]);
pAll.then(res => {
	console.log('全部執行成功', res);
}).catch(err => {
	console.log('報錯:' + err.message);// 報錯:出錯了!
}).finally(() => {
	console.log('Promise.all執行完畢');// Promise.all執行完畢
});
           
  1. Promise.race(Array[Promise] array, Function callback)

    隻要數組中有一個成功,就整個執行成功,成功回調函數的參數為最先執行成功的promise執行個體的傳回值

// ...
let pRace = Promise.race([p1, p2, p3]);
pRace.then(res => {
	console.log('至少一個執行成功', res);// 至少一個執行成功 p2-ok
});
           

async、await

async、await是generator函數的文法糖,是解決回調地獄的最新文法

async function demo() {
	let p1 = new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve('p1-ok');
		}, 1000);
	});
	
	let p2 = Promise.resolve('p2-ok');
	
	let p3 = Promise.reject(new Error('出錯了!'));

	try {
		let resAll = await Promise.all([p1, p2, p3]);
		console.log('resAll', resAll);
	} catch(err) {
		console.log('err', err.message);
	}
	
	let res = await Promise.race([p1, p2, p3]);
	console.log('race', res);
}

demo();
           

繼續閱讀