iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 14
0
Modern Web

JavaScript 忍者的修練--從下忍進階到中忍系列 第 14

Day 14: async, await

JavaScript ES6 新增了 async 函式,是一種結合了 generator 和 promise 的功能。

我們在 function 關鍵字前面加上 async 關鍵字,然後在非同步的任務前加上await關鍵字,告訴 JavaScript 說,這一段程式碼請等候它的回傳結果。收到結果後再繼續後面的執行。

function breathe(amount) {
	return new Promise((resolve, reject) => {
		if (amount < 500) {
			reject('That is too small of a value');
		}
		setTimeout(() => resolve(`Done for ${amount} ms`), amount);
	});
}

async function go () {
  const res1 = await breathe(600);
  console.log(res1);
  const res2 = await breathe(700);
  console.log(res2);
  const res3 = await breathe(800);
  console.log(res3);
}

go();

上一篇
Day 13: Promise
下一篇
Day 15: 物件原型
系列文
JavaScript 忍者的修練--從下忍進階到中忍30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言