![](/img/trans.png)
[英]How to run async functions sequentially on a React-Native app, using Expo
[英]React-Native Expo app async downloads
因此,我正在使用create-react-native-app構建項目。 您可能知道,在開發應用程序時,它使用Expo作為框架。
我正在使用Expo的FileSystem.downloadAsync()下載我需要的文件。 我需要下載多個文件,因此我在.map()中運行此命令,如下所示:
this.state.files.map(file => {
FileSystem.downloadAsync(file.url, FileSystem.documentDirectory + file.name)
.then(({ uri }) => console.log('Saved this file at: ' + uri))
.catch(console.log('Error when downloading file.'))
})
現在,使用.then(),我知道每個文件的下載時間,但是如何知道所有文件的下載時間呢?
如果我將其放在函數中並調用它,它不會等待它完成,而是會繼續執行下一段代碼。
我能以某種方式使該函數返回一個新的Promise嗎? 我認為這是一種正確的方法,但是我不確定該怎么做? 我在哪里下定決心和拒絕?
看起來您需要Promise.all()
! 它將除了一個諾言數組之外,然后返回一個新的諾言,該諾言將在數組中的每個諾言返回結果之后解決。
如果您在expo docs中查看有關預加載和緩存資產的信息,您將看到一個很好的例子。
async _loadAssetsAsync() {
const imageAssets = cacheImages([
'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png',
require('./assets/images/circle.jpg'),
]);
const fontAssets = cacheFonts([FontAwesome.font]);
// Notice how they create an array of promises and then spread them in here...
await Promise.all([...imageAssets, ...fontAssets]);
}
在您的情況下,這樣的事情會起作用
const assets = this.state.files.map(file =>
FileSystem.downloadAsync(file.url, FileSystem.documentDirectory + file.name)
)
/// Here is where you put the try.
try {
await Promise.all(assets);
} catch (error) {
/// Here is where you would handle an asset loading error.
console.error(error)
}
console.log("All done loading assets! :)");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.