티스토리 뷰

🌈 JavaScript

Callback function 만들기

James Wetzel 2023. 9. 7. 11:33

Callback 함수(function)의 핵심은 함수(function)를 파라미터(parameter)로 전송 할 수있다는 것이다.

1. 함수(function)를 파라미터(parameter)로 전송하고

2. 전송 받은 함수(function)를 실행한다는 것이다.

function fetchData(callback) {
  // Simulating an asynchronous operation (e.g., fetching data from a server)
  setTimeout(function() {
    const data = 'Sample data';
    const test = "soem text";
    
    callback(data, test); // Invoke the callback function with the fetched data
  }, 2000);
}

function processFetchedData(data, test) {
  console.log('Processing the fetched data:', data, test);
}

// Calling the fetchData function and passing processFetchedData as a callback
fetchData(processFetchedData);

 

function fetchData(callback) {
  // Simulating an asynchronous operation (e.g., fetching data from a server)
  setTimeout(function() {
    const data = 'Sample data';
    const test = "soem text";
    
    callback(data, test); // Invoke the callback function with the fetched data
  }, 2000);
}

// Calling the fetchData function and passing processFetchedData as a callback
fetchData(
	function(data, test) {
  	console.log('Processing the fetched data:', data, test);
	}
);

 

await & async 활용편

function fetchData() {
  return new Promise(function(resolve, reject) {
    // Simulating an asynchronous operation (e.g., fetching data from a server)
    setTimeout(function() {
      const data = 'Sample data';
      resolve(data); // Resolve the promise with the fetched data
    }, 2000);
  });
}

function processFetchedData(data) {
  console.log('Processing the fetched data:', data);
}

async function fetchAndProcessData() {
  try {
    const data = await fetchData(); // Await the promise to resolve
    processFetchedData(data);
  } catch (error) {
    console.error('An error occurred:', error);
  }
}

// Calling the async function
fetchAndProcessData();

 

 

비고]

팝업창에서 부모창의 특정 함수를 변수로 받아서 함수 형태로 호출 하는 방법

"eval()" 함수는 소스 코드를 javascript 코드로 변환한다.(The source is parsed as a script.)

eval("opener." + callBackFunc)(sku_info, packing_info, multi_pattern);

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함