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 . , then .