我正在使用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中,在“then”下)。 发生了什么事?
答案 0 :(得分:1)
只需在第一个承诺中解决您的输出。
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;
})
}
使用new Promise
和resolve
初始化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/primers/promises#whats-all-the-fuss-about