Js/async
รุ่นแก้ไขเมื่อ 18:13, 5 กรกฎาคม 2563 โดย Jittat (คุย | มีส่วนร่วม) (สร้างหน้าด้วย "== Code เริ่มต้น == <syntaxhighlight lang="javascript"> function doSomething(msg) { let t = Math.random()*1500; setTimeout(() => {...")
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 main2() {
return (main()
.then((x) => { return doSomething(" Z " + x); }));
}
async function main2alternative() {
let x = await main();
await doSomething(" Z " + x);
}
async function main3() {
await main2();
await doSomething("---------");
}
console.log("----started----");
main3();
console.log("---------------");