下面是我的代码,用于读取已经下载并存储在“TemporaryDirectoryPath”中的JSON文件。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let currentPackage = self.packages[indexPath.section]
switch indexPath.row {
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "PromoButtonCell") as! PromoButtonCell
cell.populate(currentPackage)
cell.contentView.tag = (indexPath.section + 1) * 10
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "CommonPromoCell") as! CommonPromoCell
cell.populate(currentPackage, forPayment: self.payments[self.paymentIndex].type)
cell.optionBtnCommon.tag = indexPath.section
return cell
我得到一个类型为“Promise”的对象,如下所示
var fileName = getFileNameFromUrl(url);
RNFS.downloadFile({
fromUrl: url,
toFile: `${RNFS.TemporaryDirectoryPath}/`+fileName
}).promise.then(r => {
var content = RNFS.readFile(`${RNFS.TemporaryDirectoryPath}/`+fileName, 'utf8');
console.log(content);
});
如何从Promise对象中读取内容?
答案 0 :(得分:2)
为什么不用“导入”
导入它import AnyName from './pathToYourJSONfile';
我必须在这里写,低代表添加评论! :/
答案 1 :(得分:0)
您已经知道RNFS.readFile()
返回Promise
。
因此,您只需要学习如何使用Promise
。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
var fileName = getFileNameFromUrl(url);
RNFS.downloadFile({
fromUrl: url,
toFile: `${RNFS.TemporaryDirectoryPath}/` + fileName
})
.then(r => {
RNFS.readFile(`${RNFS.TemporaryDirectoryPath}/` + fileName, 'utf8')
.then(content => {
console.log(content);
})
});
答案 2 :(得分:0)
我遇到了同样的问题,并通过以下内容设法获得了内容:
let asset_content = null;
try {
await RNFetchBlob.fs.readFile(assetFile_path, 'utf8')
.then((data) => {
asset_content = data;
console.log("got data: ", data);
})
.catch((e) => {
console.error("got error: ", e);
})
} catch (err) {
console.log('ERROR:', err);
}
const assets = JSON.parse(asset_content);
您可能还必须确保内容已另存为'utf8'