Js/async
ไปยังการนำทาง
ไปยังการค้นหา
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("---------------");