javascript - Expo FileSystem.writeAsStringAsync 不像 Promise
问题描述
我正在使用函数 Expo.writeAsStringAsync() (文档:https://docs.expo.io/versions/latest/sdk/filesystem/#filesystemwriteasstringasyncfileuri-contents-options)。我注意到它需要不同大小的文件的不同时间(如预期的那样),但是没有办法知道它何时完成,因为它什么也不返回。所以,如果我必须在写完文件后访问它,我会发现它是空的,因为它可能还在写。
完成后有什么方法可以收到答案吗?就像一个正常的承诺然后抓住?
PS:我试图承诺它,但没有成功。
解决方案
我可以看到 API 文档具有误导性,因为它们没有指定返回类型。
事实上,API 调用被定义为async
函数(参见源代码):
export async function writeAsStringAsync(
fileUri: string,
contents: string,
options: WritingOptions = {}
): Promise<void> {
// ...
}
每个async
函数都返回一个 Promise(你可以在上面的 TypeScript 签名中看到它说Promise<void>
)。
这意味着您可以使用返回的 Promise 并await
为它或使用.then()
等待文件系统调用完成的时刻。
await Expo.writeAsStringAsync(fileUri, contents, options);
// do something when write is finished
// you can catch errors with try/catch clause
或者
Expo.writeAsStringAsync(fileUri, contents, options).then(
() => { /* do something when write is finished */ }
).catch(err => { /* handle errors */ }
推荐阅读
- python - 这段代码中的-1是什么意思([file for file in os.listdir(folder_dir) if file.find("xlsx") != -1])?
- ruby-on-rails - 删除用户时如何删除用户相关数据?
- python - 使用 awk 根据某些行中的值过滤文本文件
- formula - 如何解决 LibreOffice Calc 中的函数错误
- ms-access - 如果访问查询中的语句根据订购的数量从 1 个产品中选择 2 个价格
- reactjs - 以一定间隔渲染标记
- c# - 如何使 Unity 游戏对象变量只能从检查器编辑
- android - Android 聊天气泡概述了自定义设计
- javascript - 完整日历 REACT JS - 如何禁用拖动到反向背景事件
- python - 防止 Matplotlib 将绘图拉伸到仅绘图区域的 bbox