首页 > 解决方案 > Expo FileSystem.writeAsStringAsync 不像 Promise

问题描述

我正在使用函数 Expo.writeAsStringAsync() (文档:https://docs.expo.io/versions/latest/sdk/filesystem/#filesystemwriteasstringasyncfileuri-contents-options)。我注意到它需要不同大小的文件的不同时间(如预期的那样),但是没有办法知道它何时完成,因为它什么也不返回。所以,如果我必须在写完文件后访问它,我会发现它是空的,因为它可能还在写。

完成后有什么方法可以收到答案吗?就像一个正常的承诺然后抓住?

PS:我试图承诺它,但没有成功。

标签: javascriptreact-nativepromiseexpo

解决方案


我可以看到 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 */ }

推荐阅读