Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

JavaScript - Asynchronous Function

Back


Asynchronous


Callbacks Function

list = ["apple", "banana", "cherry"];

// define a asynchronous function
const logEach = (arr, cb) => {
  arr.map((row) => {
    cb(row);
  });
};

// call the asynchronous function
// by defining an anonymous function as callback function
logEach(list, (data) => {
  console.log(data);
});

// apple
// banana
// cherry

setTimeout(): 典型回调函数

setTimeout(call_back_function, milliseconds, [param]);
console.log("\n-------- setTimeout --------\n");
// Error: callback function must be funtion(a named function or anonymous function), not codes
// setTimeout(console.log("SetTimeout"), 1000);
const cbFunc = (data) => {
  console.log(data);
};

setTimeout(cbFunc, 1000, "SetTimeout"); // SetTimeout;

setTimeout(cbFunc, 1000, "SetTimeout", "Hi"); // SetTimeout;
// "Hi" will not pass because callback function defined with only one parameter
console.log("\n-------- setTimeout --------\n");

// define a function used as callback function latter
const cbFunc = (data) => {
  console.log(data);
};

// define an asynchronous function using setTimeout() and callback function
const main = (cb, str) => {
  setTimeout(cb, 1000, str);
};

// call asynchronous function
main(cbFunc, "hello");

Promise

// create a promise
let myPromise = new Promise((resolve, reject) => {
  // Promise code here
  //resolve(data);
  //reject(new Error());
});

// call a promise
myPromise.then(() => {}).catch(() => {});
console.log("\n-------- Promise --------\n");

const waitSecond = (ms) =>
  new Promise((resolve) => {
    setTimeout(resolve, ms);
  });

console.log("1");
waitSecond(100)
  .then(() => {
    console.log("2");
  })
  .then(() => {
    console.log("3");
  });
console.log("4");

// 1
// 4
// 2
// 3

Chaining

console.log("\n-------- Promise --------\n");

// Promise
const delaySecond = (sec) =>
  new Promise((resolve) => {
    console.log("delay second:", sec);
    setTimeout(resolve, sec, sec); //the seconde sec passes it to resolve function
  });

delaySecond(1000)
  .then((data) => delaySecond(data)) //data will be 1000 because setTimeout in delaySecond() pass sec to resolve function
  .then((data) => delaySecond(data))
  .then((data) => delaySecond(data))
  .finally(() => console.log("End"));

// delay second: 1000
// delay second: 1000
// delay second: 1000
// delay second: 1000
// End

Parallel Promises: all()

// all()
const xFunc = (x) => x / 100;
const yFunc = (y) => y / 1000;

const sum = (arr) =>
  new Promise((resolve) => {
    const s = arr.reduce((acc, item) => acc + item, 0);
    resolve(s);
  });

Promise.all([xFunc(3000), yFunc(3000)])
  .then((data) => sum(data))
  .then(console.log); //33

Mixed Promises

console.log("\n-------- Promise: mix --------\n");

const delaySecond = (sec) =>
  new Promise((resolve) => {
    console.log("delay second:", sec);
    setTimeout(resolve, sec, sec);
  });

const xFunc = (x) => x / 100;
const yFunc = (y) => y / 1000;

const sum = (arr) =>
  new Promise((resolve) => {
    console.log(arr); // display result array of Promise.all()
    const s = arr.reduce((acc, item) => acc + item, 0);
    resolve(s);
  });

// delay 2 second, then wait until xFunc and yFunc finish, then sum, then log
delaySecond(2000)
  .then((data) => Promise.all([xFunc(data), yFunc(data)]))
  .then((data) => sum(data))
  .then((data) => console.log(data));

// delay second: 2000
// [ 20, 2 ]
// 22

async/await

console.log("\n-------- async/await --------\n");

// define a promise
const delaySecond = (sec) =>
  new Promise((resolve) => {
    console.log("delay second:", sec);
    setTimeout(resolve, sec, sec); // the second sec passes to resolve function, eventually is the result of the await function
  });

// define an async function
const mainChain = async (ms) => {
  const ms1 = await delaySecond(ms);
  const ms2 = await delaySecond(ms1); //using the result of previous delaySecond
  const ms3 = await delaySecond(ms2);
  console.log("End");
};

// call the async function
mainChain(2000);

// delay second: 2000
// delay second: 2000
// delay second: 2000
// End
console.log("\n-------- async/await: all() --------\n");

const xFunc = (x) => x / 100;
const yFunc = (y) => y / 1000;

const sum = (arr) =>
  new Promise((resolve) => {
    const s = arr.reduce((acc, item) => acc + item, 0);
    resolve(s);
  });

// define an async using await and Promise.all()
const mainAll = async (ms) => {
  const arr = await Promise.all([xFunc(ms), yFunc(ms)]);
  console.log(arr);
  const sumArr = await sum(arr);
  console.log(sumArr);
};

// call async function
mainAll(3000);

// [ 30, 3 ]
// 33
console.log("\n-------- async/await: mix --------\n");

const xFunc = (x) => x / 100;
const yFunc = (y) => y / 1000;

// define a promise function
const delaySecond = (sec) =>
  new Promise((resolve) => {
    console.log("delay second:", sec);
    setTimeout(resolve, sec, sec); // the second sec passes to resolve function, eventually is the result of the await function
  });

// define a promise function
const sum = (arr) =>
  new Promise((resolve) => {
    console.log(arr);
    const s = arr.reduce((acc, item) => acc + item, 0);
    resolve(s);
  });

// define an async function
const mainMix = async (ms) => {
  const sec = await delaySecond(ms);
  const arr = await Promise.all([xFunc(sec), yFunc(sec)]);
  const sumArr = await sum(arr);
  console.log(sumArr);
};

// call async function
mainMix(2000);

// delay second: 2000
// [ 20, 2 ]
// 22

TOP