ReasonJun

javascript : Async 본문

Frontend/Javasciprt

javascript : Async

ReasonJun 2023. 6. 7. 01:23
728x90

https://medium.com/@Rahulx1/understanding-event-loop-call-stack-event-job-queue-in-javascript-63dcd2c71ecd

Only one call stack can be executed at a time.

To use it asynchronously, you must use the Web API.

So, if you throw the desired callback function to this API, it performs asynchronous work internally, and when it is finished, the callback function is put in the Task Queue.

After that, the event loop of the javascript engine monitors the call stack and task queue, and only when the call stack is empty, the callback function is put into the call stack and executed.

 

function execute() {
  console.log('1');
  setTimeout(() => {
    console.log('2');
  }, 2000); // execute after 2 seconds
  console.log('3');
}
execute();
// 1
// 3
// 2

how to fix the order

function fetchEgg(chicken) {
  return Promise.resolve(`${chicken} laid an 🥚`);
}

function fryEgg(egg) {
  return Promise.resolve(`Fried ${egg} => 🍳`);
}

function getChicken() {
  return Promise.reject(new Error('no chicken available!'));
  //return Promise.resolve(`Hen => 🐔`);
}

getChicken()
  .catch(() => 'Found a 🐔')
  .then(fetchEgg)
  .then(fryEgg)
  .then(console.log); // Found a 🐔 laid an 🥚 => 🍳

 

promise

const c = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(1);
      resolve();
    }, 1000);
  });
};

const d = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(2);
      resolve();
    }, 1000);
  });
};

const e = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log(3);
      resolve();
    }, 1000);
  });
};

//
c()
  .then(() => {
    return d();
  })
  .then(() => {
    return e();
  });

//
c()
  .then(() => d())
  .then(() => e());

//
c().then(d).then(e);

const getMovies = (movieName) => {
  return new Promise((resolve) => {
    fetch(`https://www.wefwef.com/?apikey=${movieName}`)
      .then((res) => res.json())
      .then((res) => {
        console.log(res);
        resolve();
      });
  });
};

getMovies('frozen')
  .then(() => {
    console.log('겨울왕국');
    return getMovies('avengers');
  })
  .then(() => {
    console.log('어벤져스');
    return getMovies('avatar');
  })
  .then(() => {
    console.log('avatar');
  });
  
  
  
  
  
  function getBanana() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('🍌 from the tropics');
    }, 1000);
  });
}

function getApple() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('🍏 from the orchard');
    }, 3000);
  });
}

function getOrange() {
  return Promise.reject(new Error('no orange available'));
}

// Bringing Bananas and Apples Together
getBanana() //
  .then((banana) =>
    getApple() //
      .then((apple) => [banana, apple])
  )
  .then(console.log); // [ '🍌 from the tropics', '🍏 from the orchard' ] : 4 seconds total



Promise.all([getBanana(), getApple()]) //
  .then((fruits) => console.log('all', fruits)); // all [ '🍌', '🍎' ] : 3 seconds
  
  
// Promise.race 
// Among the given promises, the one that executes fastest wins!
Promise.race([getBanana(), getApple()]) //
  .then((fruit) => console.log('race', fruit)); // race 🍌 : the fastest
  



// Promise.allSettled
// Returns a promise that is fulfilled with an array of results after all the provided promises have settled, regardless of whether they fulfilled or rejected.
  
const promise1 = Promise.resolve('Resolved');
const promise2 = Promise.reject(new Error('Rejected'));
const promise3 = new Promise((resolve) => setTimeout(() => resolve('Delayed'), 2000));

Promise.allSettled([promise1, promise2, promise3])
  .then((results) => {
    results.forEach((result) => {
      if (result.status === 'fulfilled') {
        console.log(`Fulfilled: ${result.value}`);
      } else if (result.status === 'rejected') {
        console.log(`Rejected: ${result.reason}`);
      }
    });
  });

//Fulfilled: Resolved
//Rejected: Error: Rejected
//Fulfilled: Delayed

fetch

// fetch(address, option)
// Requests and responses of resources can be processed through the network.
// Returns a Promise instance.

console.log(fetch('<https://www.omdapi.com/?apikey=wefdvds&s=avengers>'));
// Promise {  }

const res = await fetch('<https://www.omdapi.com/?apikey=wefdvds&s=avengers>');

const wrap = async () => {
  const res = await fetch('<https://www.omdapi.com/?apikey=wefdvds&s=avengers>');
  const json = await res.json();
  console.log(json);
};

wrap();

// defalut is 'get'
fetch('<https://www.omdapi.com/?apikey=7035c60c&s=avengers>', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'youjun',
    age: 85,
  }),
});

fetch('<https://www.omdapi.com/?apikey=7035c60c&s=avengers>', {
  method: 'POST',
});

resolve / reject => error handling

const delayAdd1 = (index) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (index > 10) {
        reject(`${index}is not much more than 10`);
        return;
      }
      console.log(index);
      resolve(index + 1);
    }, 1000);
  });
};

delayAdd1(13)
  .then((res) => console.log(res)) // resolve
  .catch((err) => console.error(err)) // reject
  .finally(() => console.log('Done'));

const wrap = async () => {
  const res = await delayAdd1(7);
  console.log(res);
};
wrap();

// finallyis always execute

const wrap1 = async () => {
  try {
    const res = await delayAdd1(11);
    console.log(res);
  } catch (err) {
    console.error(err);
  } finally {
    console.log('Done');
  }
};

wrap1();

callback hell 

const a = () => {
  setTimeout(() => {
    console.log(1);
  }, 1000);
};
const b = () => console.log(2);

a();
b();

// When you want the number 1 to come first, followed by the number 2

const c = (callback) => {
  setTimeout(() => {
    console.log(1);
    callback();
  }, 1000);
};

const d = (callback) => {
  setTimeout(() => {
    console.log(2);
    callback();
  }, 1000);
};

const e = () => console.log(3);

// callback hell 
c(() => {
  d(() => {
    e();
  });
});

=> use async() => {  await functionName('') }

const getMovies = (movieName) => {
  return new Promise((resolve) => {
    fetch(`https://www.wefwef.com/?apikey=${movieName}`)
      .then((res) => res.json())
      .then((res) => {
        console.log(res);
        resolve();
      });
  });
};

// await can only be applied to functions that return promise instances.
const wrap1 = async () => {
  await getMovies('frozen');
  console.log('겨울왕국');
  await getMovies('avengers');
  console.log('어벤져스');
  await getMovies('avatar');
  console.log('아바타');
};

wrap1();


function getBanana() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('🍌 from the farm');
    }, 1000);
  });
}

function getApple() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('🍏 from the orchard');
    }, 3000);
  });
}

function getOrange() {
  return Promise.reject(new Error('no orange available'));
}

// Bringing Bananas and Apples Together
async function fetchFruits() {
  const banana = await getBanana(); // await : When the promise of getBanana() resolves, the value is assigned to a variable.
  const apple = await getApple();
  return [banana, apple]; // async : Wait until all returned promises are resolved before returning.
}

fetchFruits() //
  .then((fruits) => console.log(fruits));
728x90
Comments