我知道这是 RN 中一个非常常见的问题,我仍在尝试了解从属性文件加载数据时返回 Promise 的可能优势,而不是仅仅返回值,这使得链接请求非常麻烦......但无论如何。这是我现在拥有的,它是 AsyncStorage RN 实现的包装器:
multiGet = async (key) => {
var value = null;
try {
value = await AsyncStorage.multiGet(key).then(
(values) => {
value = values;
console.log('Then: ',values);
});
} catch (error) {
console.log('Error: ',error);
}
console.log('Final: ',value);
return value;
}
此时,值变得不确定。在我的主要代码中我有这个:
var filter = this._getFilter();
console.log('returned filter:',filter);
_getFilter 函数是使用 AsyncStorage 包装器的函数,但“返回的过滤器”在第一个函数之前进行记录,因此它不会在继续之前等待返回值,因此我得到一个未定义的值。
起初,我认为只要使用 async/await,AsyncStorage 就会返回一个值而不是承诺,但经过测试,我得到的值是:
value = await AsyncStorage.getItem('key')
仍然是一个承诺,所以我必须使用 then() 来读取该值。
基本上我在日志中看到的顺序是:
_getFilter
returned value: undefined
Then: value: here I get the correct value from the keys but the code already passed and I don't have the correct value in the variable
我不知道发生了什么或如何正确处理这个问题。这应该是非常简单且常见的用例。
我很想在不使用第三方模块的情况下解决这个问题。
Thanks
SOLUTION编辑:在更多地了解异步/等待和回调的概念之后,我终于有了一个可以工作的代码。我不喜欢它,因为它使代码很难阅读。我可能需要重构它以使用承诺,但现在它可以工作。以下是一些片段,以防有人发现同样的问题:
this._getFilter(body,this._filterSearchCallback,callback);
注意:我通过链发送正文,因为我在传递函数时“完成”信息。第二个参数是实际进行 fetch 查询的第一个回调,第三个回调是 fetch 函数的返回。
_getFilter(body,callback,returnCallback){
{...}
this._sh.multiGet(keysBanks).then(
(banks) => {
filter.banks = banks;
console.log(banks);
this._sh.multiGet(keysCards).then(
(cards) => {
console.log(cards);
filter.credit_cards = cards;
callback(body,filter,returnCallback);
});
}
);
}
基本上,我在这里链接了几个获取,因为我需要来自商店的多个值。这是我不太喜欢的部分。 _sh 是我的 StorageHelper,它是 AsyncStorage 的包装器,没什么花哨的。
multiGet = async (key) => {
const value = await AsyncStorage.multiGet(key);
return value;
}
然后我的最后一个回调实际上在 React Native 中进行获取并将 JSON 响应发送到主屏幕:
_filterSearchCallback(body,filter,callback){
body.filter = filter;
return fetch(apiUrl, {method: 'post', body: JSON.stringify(body)})
.then((response) => response.json())
.then((responseJson) => {
callback(responseJson);
})
.catch((error) => {
console.error(error);
callback(responseJson);
});
}
我会改进它并使其更干净,但现在它有效。希望它也能帮助其他人。