Just trying out Promises for the first time in React. I have a basic promise working (ripped from someone else's code), but don't know how to adapt it to be useful.
What I have so far (within my render()
function)
var promise = new Promise( (resolve, reject) => {
let name = 'Dave'
if (name === 'Dave') {
resolve("Promise resolved successfully");
}
else {
reject(Error("Promise rejected"));
}
});
promise.then(function(result) {
console.log(result); // "Promise resolved successfully"
}, err => {
console.log(err); // Error: "Promise rejected"
});
Sure enough, as the promise conditional is matched (name === 'Dave'
), my console logs Promise resolved successfully
.
However, I don't know how to assign a value to a variable when using the promise. For example:
promise.then(function(result) {
var newName = 'Bob'
}, function(err) {
var newName = 'Anonymous'
});
And then when I try to return this value in render()
's return statement, like so:
<h2>{newName}</h2>
It says newName is undefined.
I have also tried:
promise.then(function(result) {
var newName = result
}, function(err) {
var newName = error
});
...expecting this would assign the resolve
or error
string into newName
variable, but nope.
Am I thinking about this the wrong way? How can I make this more useful than just logging a string when my conditional is met?
Any help would be appreciated, because this is really making my head hurt...
Update
render() {
var promise = new Promise( (resolve, reject) => {
let name = 'Paul'
if (name === 'Paul') {
resolve("Promise resolved successfully");
}
else {
reject(Error("Promise rejected"));
}
});
let obj = {newName: ''};
promise.then( result => {
obj["newName"] = result
}, function(error) {
obj["newName"] = error
});
console.log(obj.newName)
return (
<div className="App">
<h1>Hello World</h1>
<h2>{obj.newName}</h2>
</div>
);
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…