function myPromise() {
return new Promise((resolve, reject) => {
let i = 0;
while (i < 1000000000) {
i++;
}
resolve();
})
}
console.log('start');
myPromise();
console.log('end');
What's going on here?. The answer is easy, the promise cannot be resolved until the while loop is ends.
To solve this we can do this.
function myPromise2() {
return Promise.resolve().then(() => {
let i = 0;
while (i < 1000000000) {
i++;
}
});
}
console.log('start');
myPromise2();
console.log('end');
Now this is async because our code is inside Promise.resolve(). Try to run this now.
Reference copy
Sure you know (Spread Operator). This operator we used to do several operations like assigning properties or values, not copying object reference.
const arr1 = [
{id: 1, name: 'php'},
{id: 2, name: 'ruby'},
];
const arr2 = [...arr1];
// but it doesn't copy the array reference but it does copy the object
console.log('arr1', arr1);
console.log('arr2', arr2);
const [obj] = arr2;
obj.id = 300000;
obj.name = 'OHHH';
console.log('arr1', arr1);
console.log('arr2', arr2);
We saw that spread operator doesn't work. Why?. Well spread operator works but only the first level, To solve this, we need to iterate each element of the array and apply the spread operator.
We used the funcion map, this function returns a new array, so it doesn't copy the array reference and apply spread operator to each object inside of the array. But we imagine that it has a more complicated object.
A typical mistake, for example, is something that this.
const a = null;
const b = [];
const c = {};
const d = 1;
const e = NaN;
console.log('null and [] is: ' + (typeof a === typeof b).toString());
console.log('[] and {} is: ' + (typeof b === typeof c).toString());
console.log('1 and NaN is: ' + (typeof d === typeof e).toString());
Top comments (0)