development

nodeJs 콜백 간단한 예

big-blog 2020. 7. 25. 10:13
반응형

nodeJs 콜백 간단한 예


어느 누구도 nodeJs 콜백의 간단한 예를 제공 할 수 있습니까, 이미 많은 웹 사이트에서 동일한 것을 검색했지만 제대로 이해할 수는 없습니다. 간단한 예를 들어주십시오.

getDbFiles(store, function(files){
    getCdnFiles(store, function(files){
    })
})

나는 그런 것을하고 싶다 ...


var myCallback = function(data) {
  console.log('got data: '+data);
};

var usingItNow = function(callback) {
  callback('get it?');
};

이제 노드 또는 브라우저 콘솔을 열고 위 정의를 붙여 넣습니다.

마지막으로 다음 줄과 함께 사용하십시오.

usingItNow(myCallback);

노드 스타일 오류 규칙을 준수

Costa는 노드 오류 콜백 규칙을 준수 할 것인지를 물었습니다.

이 규칙에서 콜백은 하나 이상의 인수 인 첫 번째 인수를 오류로 수신해야합니다. 선택적으로 상황에 따라 하나 이상의 추가 인수가 있습니다. 이 경우 컨텍스트는 위의 예입니다.

이 컨벤션에서 예제를 다시 작성합니다.

var myCallback = function(err, data) {
  if (err) throw err; // Check for the error and throw if it exists.
  console.log('got data: '+data); // Otherwise proceed as usual.
};

var usingItNow = function(callback) {
  callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument
};

오류 사례를 시뮬레이션하려면 다음과 같이 itItNow를 사용하여 정의 할 수 있습니다.

var usingItNow = function(callback) {
  var myError = new Error('My custom error!');
  callback(myError, 'get it?'); // I send my error as the first argument.
};

최종 사용법은 위와 동일합니다.

usingItNow(myCallback);

동작의 유일한 차이점 usingItNow은 정의한 버전에 따라 결정됩니다. 첫 번째 인수의 콜백에 "truthy value"(오류 객체)를 제공하는 버전이나 오류 인수의 경우 null을 제공하는 버전 .


콜백 함수는 단순히 함수를 나중에 호출 할 수 있도록 다른 함수에 전달하는 함수입니다. 이것은 일반적으로 비동기 API 에서 볼 수 있습니다 . API 호출은 비동기식이므로 즉시 반환되므로 비동기 작업 수행이 완료되면 API가 호출 할 수있는 함수를 전달합니다.

The simplest example I can think of in JavaScript is the setTimeout() function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.

setTimeout(function () {
  console.log("10 seconds later...");
}, 10000);

You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.

var callback = function () {
  console.log("10 seconds later...");
};
setTimeout(callback, 10000);

Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs library to read a file. The fs module exposes two unique API functions: readFile and readFileSync.

The readFile function is asynchronous while readFileSync is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile and readFileSync instead of readFile and readFileAsync. Here is an example of using both functions.

Synchronous:

var data = fs.readFileSync('test.txt');
console.log(data);

The code above blocks thread execution until all the contents of test.txt are read into memory and stored in the variable data. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.

Asynchronous (with callback):

var callback = function (err, data) {
  if (err) return console.error(err);
  console.log(data);
};
fs.readFile('test.txt', callback);

First we create a callback function that accepts two arguments err and data. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err has a value before you do anything else. If so, stop execution of the callback and log the error.

Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch block.

try {
  var data = fs.readFileSync('test.txt');
  console.log(data);
} catch (err) {
  console.error(err);
}

In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.

In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.


Here is an example of copying text file with fs.readFile and fs.writeFile:

var fs = require('fs');

var copyFile = function(source, destination, next) {
  // we should read source file first
  fs.readFile(source, function(err, data) {
    if (err) return next(err); // error occurred
    // now we can write data to destination file
    fs.writeFile(destination, data, next);
  });
};

And that's an example of using copyFile function:

copyFile('foo.txt', 'bar.txt', function(err) {
  if (err) {
    // either fs.readFile or fs.writeFile returned an error
    console.log(err.stack || err);
  } else {
    console.log('Success!');
  }
});

Common node.js pattern suggests that the first argument of the callback function is an error. You should use this pattern because all control flow modules rely on it:

next(new Error('I cannot do it!')); // error

next(null, results); // no error occurred, return result

Try this example as simple as you can read, just copy save newfile.js do node newfile to run the application.

function myNew(next){
    console.log("Im the one who initates callback");
    next("nope", "success");
}


myNew(function(err, res){
    console.log("I got back from callback",err, res);
});

we are creating a simple function as

callBackFunction (data, function ( err, response ){
     console.log(response)
}) 

// callbackfunction 
function callBackFuntion (data, callback){
    //write your logic and return your result as
callback("",result) //if not error
callback(error, "") //if error
}

const fs = require('fs');

fs.stat('input.txt', function (err, stats) {
    if(err){
        console.log(err);
    } else {
        console.log(stats);
        console.log('Completed Reading File');
    }
});

'fs' is a node module which helps you to read file. Callback function will make sure that your file named 'input.txt' is completely read before it gets executed. fs.stat() function is to get file information like file size, date created and date modified.


A callback is a function passed as an parameter to a Higher Order Function (wikipedia). A simple implementation of a callback would be:

const func = callback => callback('Hello World!');

To call the function, simple pass another function as argument to the function defined.

func(string => console.log(string));

참고URL : https://stackoverflow.com/questions/19739755/nodejs-callbacks-simple-example

반응형