我正在使用 react-native-simple-store
,试图读取值的值。
在 constructor
中定义了这一点:
this.checkIfTermsAgreedTo = this.checkIfTermsAgreedTo.bind(this);
使用此功能
checkIfTermsAgreedTo(){
return new Promise((resolve,reject) => {
return store.get('agreed');
})
.then(agreed =>{
console.log(agreed); --> This line is never reached
console.log((agreed.terms == "YES") ? "AGREED!" : "Not agreed....");
return agreed;
})
}
使用componentWillMount
中的承诺如下:
componentWillMount(){
this.checkIfTermsAgreedTo().then(agreed=>{
this.setState({agreed:(agreed.terms == "YES")});
})
.catch(()=>{
console.log("CATCH: Agreed, probably not found");
this.setState({agreed:{terms:"NO"}})}
);
}
从未达到指定的线路。(在checkiftermsagreedto中,在"然后"下)。发生了什么?
只需在第一个承诺中解决您的输出。
checkIfTermsAgreedTo(){
return new Promise((resolve,reject) => {
resolve(store.get('agreed'));
})
.then(agreed =>{
console.log(agreed); --> This line is never reached
console.log((agreed.terms == "YES") ? "AGREED!" : "Not agreed....");
return agreed;
})
}
当您使用resolve
初始化new Promise
和reject
时,请记住,resolve
和reject
不过是您在then
中传递的功能块。例如。
var i = 100;
var k = new Promise((resolve, reject) => {
if(i === 100)
resolve("I AM RESOLVED BY YOUR FIRST FUNCTION BLOCK")
else
reject("I AM REJECTED BY YOUR SECOND FUNCTION BLOCK")
})
// Now when you resolve the promise like below, the `thenable` struct
// will expect two function blocks or atleast one which are the
// success(resolve) and error(reject) blocks
resolveBlock = (response) => {
console.log(response);
}
rejectBlock = (reject) => {
console.log(reject);
}
k.then(resolveBlock, rejectBlock);
// I AM RESOLVED BY YOUR FIRST FUNCTION BLOCK
// OR IT CAN BE WRITTEN AS BELOW WHICH IS THE USUAL NORM
// k.then((response) => {
// console.log(response);
// }, (reject) => {
// console.log(reject);
// })
这是入门/修订 Promises
https://developers.google.com/web/fundamentals/promiss/promises#whats-whats-promiss#whats-all-thats-fuss-fuss-about-about-p./p>