Reputation: 121
I'm learning about Promise in Javascript. But when I tried to write some lines of code, I have this problem. My "if" statement, which I declare inside a Promise Obj always return true. Here's information:
var status = false;
var promise = new Promise(function(resolve, reject) {
if (status) {
console.log("TRUE")
resolve({
value: 'true'
});
} else {
console.log("FALSE");
reject({
value: 'false'
});
}
});
Upvotes: 3
Views: 562
Reputation: 943579
status
is a predefined variable in browsers.
When you assign a value to it, it is cast to a string.
false
becomes "false"
which is a true value.
This is why you should avoid globals. Conflicts with other people's variables are never fun.
Wrap your code in an IIFE to avoid trying to create variables in the global scope.
(function() {
var status = false;
var promise = new Promise(function(resolve, reject) {
if (status) {
console.log("TRUE")
resolve({
value: 'true'
});
} else {
console.log("FALSE");
reject({
value: 'false'
});
}
});
}());
Upvotes: 9