Js/async

จาก Theory Wiki
รุ่นแก้ไขเมื่อ 18:13, 5 กรกฎาคม 2563 โดย Jittat (คุย | มีส่วนร่วม) (→‎Async / await)
(ต่าง) ←รุ่นแก้ไขก่อนหน้า | รุ่นแก้ไขล่าสุด (ต่าง) | รุ่นแก้ไขถัดไป→ (ต่าง)
ไปยังการนำทาง ไปยังการค้นหา

Code เริ่มต้น

function doSomething(msg) {
  let t = Math.random()*1500;
  setTimeout(() => {
    console.log(msg + "  " + t);
  }, t);
}

console.log("----started----");
doSomething("A         ");
doSomething("  B       ");
doSomething("    C     ");
doSomething("      D   ");
doSomething("        E ");      
console.log("---------------");

Callback

function doSomething(msg, callback) {
  let t = Math.random()*1500;
  setTimeout(() => {
    console.log(msg + "  " + t);
    if (callback !== undefined) callback();
  }, t);
}

console.log("----started----");
doSomething("A         ", () => {
  doSomething("  B       ", () => {
    doSomething("    C     ", () => {
      doSomething("      D   ", () => {
        doSomething("        E ");      
      });    
    });  
  });
});
console.log("---------------");

Promise

function doSomething(msg) {
  return new Promise((resolve,reject) => {
    let t = Math.random()*1500;
    setTimeout(() => {
      console.log(msg + "  " + t);
      resolve();
    }, t);
  });  
}

console.log("----started----");
doSomething("A         ")
  .then(() => {return doSomething("  B       ")})
  .then(() => {return doSomething("    C     ")})
  .then(() => {return doSomething("       D  ")})
  .then(() => {return doSomething("         E")});
console.log("---------------");

Async / await

function doSomething(msg) {
  return new Promise((resolve,reject) => {
    let t = Math.random()*1500;
    setTimeout(() => {
      console.log(msg + "  " + t);
      resolve();
    }, t);
  });  
}

async function main() {
  await doSomething("A         ");
  await doSomething("  B       ");
  await doSomething("    C     ");
  await doSomething("       D  ");
  await doSomething("         E");
  return 10;
}

function main2alternative() {
  return (main()
            .then((x) => { return doSomething(" Z " + x); }));
}

async function main2() {
  let x = await main();
  await doSomething(" Z " + x);
}

async function main3() {
  await main2();
  await doSomething("---------");
}

console.log("----started----");
main3();
console.log("---------------");