I am learning the ES6 standard so I start from a very basic example code.
There are callback hells exist in JavaScript so this time I do want to avoid using callbacks. But I met a problem that I don't really know how to convert a callback style code to a promise.
For example, if I have such code looks like 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 should I convert it to a Promise
in ES6? Is that a kind of recommended behavior that convert callbacks to promises?
I have read this example but I was actually confused by the result. I think before I start 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
My understanding is that Promise
runs immediately after getting created. But I don't know why the code in then
method will be run last.