How to convert callback code to ES6

I am learning the ES6 standard, so I start with a very simple code example.

There are callbacks in JavaScript, so this time I want to avoid using callbacks. But I ran into a problem that I really don't know how to convert the callback style code to a promise.

For example, if I have such a code below

module.exports = (x, y, callback) => {
  try {
    if (x < 0 || y < 0) {
      throw new Error('Rectangle dimensions are wrong.');
    } else {
      callback(null, {
        perimeter() {
          return (2 * (x + y));
        },
        area() {
          return (x * y);
        },
      });
    }
  } catch (error) {
    callback(error, null);
  }
};

How do I convert it to Promisein ES6? Is this the recommended behavior that converts callbacks to promises?

I read this example, but I was really confused by the result. I think, before I begin to rewrite my callbacks to promises, I need to understand this first.

let promise = new Promise(function(resolve, reject) {
  console.log('Promise');
  resolve();
});

promise.then(function() {
  console.log('Resolved.');
});

console.log('Hi!');

// Promise
// Hi!
// Resolved 

, Promise . , then .

+4
4

-. , API Promise. . , , , .

, -, Promises , . , SO . , Promises ?

, Promises, :

module.exports = (x, y) => {
  if (x < 0 || y < 0) {
    return Promise.reject(new Error('Rectangle dimensions are wrong.'));
  } else {
    return Promise.resolve({
      perimeter() {
        return (2 * (x + y));
      },
      area() {
        return (x * y);
      },
    });
  }
};

// e.g. success
createRectangle(10, 10)
  .then(rect => {
    console.log(rect.area()) //=> 100
  })

// e.g. failure
createRectangle(-1, -1)
  .catch(err => {
    console.log(err) //=> "Error: Rectangle dimensions are wrong."
  })

, Promise#resolve Promise#reject, Promise , "". , , .

+2
module.exports = (x, y, callback) => {
  new Promise(function(resolve, reject) {
    if (x < 0 || y < 0) reject(new Error('Rectangle dimensions are wrong.'))
    else resolve({
      perimeter() {
        return (2 * (x + y));
      },
      area() {
        return (x * y);
      }
    })
  })
  .then(callback)
  .catch(callback)
}

, ".then" ".catch" .

0

. promises callback then. , ​​ , then. , . - Node.

module.exports = (x, y, callback) => {
  try {
    if (x < 0 || y < 0) {
      throw new Error('Rectangle dimensions are wrong.');
    } else {
      callback(null, {
        perimeter() {
          return (2 * (x + y));
        },
        area() {
          return (x * y);
        },
      });
    }
  } catch (error) {
    callback(error, null);
  }
};

:

var moduleExports = (x, y, callback) => {
  try {
    if (x < 0 || y < 0) {
      throw new Error('Rectangle dimensions are wrong.');
    } else {
      callback(null, {
        perimeter() {
          return (2 * (x + y));
        },
        area() {
          return (x * y);
        },
      });
    }
  } catch (error) {
    callback(error, null);
  }
};

function promisfy(fun, ...args){
  return new Promise((v,x) => fun(...args, (err,data) => !!err ? x(err) : v(data)));
}

var p = promisfy(moduleExports,4,5);
p.then(val => console.log(val,val.area(),val.perimeter()), err => console.log(err));

// p.then(val => callback(null,val), err => callback(err))
Hide result

, area perimeter, then onFulfillment . , , onFulfillment (then ) onReject (then ). .

PS: v ( check) resolve x () reject promises.

0

Promises , , :

module.exports = (x, y) => {
var deferred = q.defer();// this will be our promise
  try {
    if (x < 0 || y < 0) {
      //return an error to be catched by catch method
      deferred.reject(new Error('Rectangle dimensions are wrong.'));
    } else {
      //return the event to the next function with this value
      deferred.resolve({
        perimeter() {
          return (2 * (x + y));
        },
        area() {
          return (x * y);
        },
      });
    }
  } catch (error) {
    deferred.reject(error);
  }

 return deferred.promise; //Here return the promise
};

//You will use it like this
module(x,y)
.then(callback)
.then(function(data){
 })
.catch(function(error){
});

In my example, when you call your module, you will immediately receive a promise, but the code has not been executed yet, after executing the code you will receive an event in your "next" method or if something happens in your catch.

I really like the q-library for processing promises, it gives you a lot of control over how to return errors and stop the chain if something is wrong. Basically, you have more control over your flow of functions.

I hope he helps you

-1
source

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


All Articles