Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ECMAScript Promise

yutasuzuki
January 14, 2018

ECMAScript Promise

第2回名古屋若手Webエンジニア交流会のLTで発表させていただいた資料です。
主にJavaScriptのPromiseを使った機能の紹介しています。
口頭で説明している部分が多いので、テキストにほぼ起こしていません。

yutasuzuki

January 14, 2018
Tweet

More Decks by yutasuzuki

Other Decks in Programming

Transcript

  1. function sleep(time) { return new Promise(function (resolve) { setTimeout(function ()

    { resolve(time) }, time); }); } sleep(3000).then(function (time) { console.log(time * 3); // 3ඵޙʹ9000Λදࣔ });
  2. function sleep(time, callback) { setTimeout(function () { callback(time) }, time);

    } sleep(3000, function (time) { // 3ඵޙʹ9000Λදࣔ console.log(time * 3); }); function sleep(time) { return new Promise(function (resolve) { setTimeout(function () { resolve(time) }, time); }); } sleep(3000).then(function (time) { // 3ඵޙʹ9000Λදࣔ console.log(time * 3); });
  3. function ajax(URL) { return new Promise(function (resolve, reject) { var

    req = new XMLHttpRequest(); req.open('GET', URL, true); req.onload = function () { if (req.status === 200) { resolve(req.responseText); } else { reject(new Error(req.statusText)); } }; req.onerror = function () { reject(new Error(req.statusText)); }; req.send(); }); } ఆٛ ajax('/api/foo') .then(function success(value){ console.log(value); }) .catch(function error(err){ console.error(err); }); ࣮ߦ
  4. ajax('/api/foo') .then(function success(value){ return ajax('/api/foo/bar/' + value) }) .then(function success(value){

    return ajax('/api/foo/bar/buz/' + value) }) .then(function success(value){ console.log(value) }) ajax('/api/foo') .then(function success(value){ ajax('/api/foo/bar/' + value) .then(function success(val)){ ajax('/api/foo/bar/buz/' + val) .then(function success(v)){ console.log(v) }) }) })
  5. function sleep(time) { return new Promise(function (resolve) { setTimeout(function ()

    { resolve(time) }, time); }); } async function call(time) { var sleepTime = await sleep(time) console.log(sleepTime * 2) } call(1000) // 1ඵޙʹ2000Λදࣔ window.addEventListener('click', async function(){ var sleepTime = await sleep(2000) console.log(delayTime * 3) // 2ඵޙʹ6000Λදࣔ })
  6. const items = [fetch(‘/api/item/1’), fetch(‘/api/item/2’)] function getItemPromises() { for (const

    item of items) { console.log(item) // get promise } } async function getItemContexts() { for await (const item of items) { console.log(item) // get api response } } getItemPromises() getItemContexts()
  7. async function main() { const { Person } = await

    import("./Person.js") const p = new Person("Yuta") p.say() // I’m Yuta } main() main.js Person.js export class Person { constructor(name = "foo") { this.name = name } say() { console.log("I'm " + this.name) } }