Why does node prefer an error callback?

Node programmers have traditionally used this paradigm:

var callback = function(err, data) {
    if (err) { /* do something if there was an error */ }

    /* other logic here */

};

Why not simplify the function to accept only one parameter, which is either an error or an answer?

var callback = function(data) {
    if (isError(data)) { /* do something if there was an error */ }

    /* other logic here */

};

It seems easier. The only drawback I see is that functions cannot return errors as their actual estimated return value, but I find this to be an incredibly minor use case.

Why is an error template considered standard?

EDIT: Implementation isError:

var isError = function(obj) {
    try { return obj instanceof Error; } catch(e) {}
    return false;
};

: , , node, , , , ?

+6
2

(. "" npm .)

. Node , , , , , , .

Node , - , err - , , - , .

request(url, (err, res, data) => {
  if (err) {
    // you have error
  } else {
    // you have both res and data
  }
});

. .

, , .

Node - , Ryan Dahl, , . , , , , - , - , async .

, , Node - , Node . , .

JavaScript Node , , , , , - , , if, Node , , .

, :

nodeStyle(params, function (err, data) {
  if (err) {
    // error
  } else {
    // success
  }
};

yourStyle(params, function (data) {
  if (isError(data)) {
    // error
  } else {
    // success
  }
};

promiseStyle(params)
  .then(function (data) {
    // success
  })
  .catch(function (err) {
    // error
  });

Promises , , , Bluebird .

, promises , :

, , , Node , promises, promisify asCallback Bluebird. , , , .

Update

npm, , :

:

npm install errc --save

:

var errc = require('errc');
var fs = require('fs');

var isError = function(obj) {
  try { return obj instanceof Error; } catch(e) {}
  return false;
};

var callback = function(data) {
  if (isError(data)) {
    console.log('Error:', data.message);
  } else {
    console.log('Success:', data);
  }
};

fs.readFile('example.txt', errc(callback));

:

, , MIT npm, , .

Node, API-, . , Node.

+3

API, , .

, - , .

Joyent even , :

- . ( ), - , . , (err, ), , .

+3

Source: https://habr.com/ru/post/1660316/


All Articles