Dom
Dom

Reputation: 1427

Wait for async function

I'm aware this is a common problem asked by developers but I can't seem to find anyone who has the same issue as me.

I've got a game i'm creating, this game has lots of factories that when called return a game object, such as a player. Before the game even starts, i need to make sure all the images required are loaded, i did this by simply converting the .onload event into a promise, and placing that into an async function with an await call. However, due to changes in how i'm organizing the game, i will need to handle image loading in those factories that create game objects. This is a problem because now the game doesn't know when all the images are loaded. I thought I might be able to make those factories asynchronous and await on them, they will have an async function call that is also awaited on, but I don't believe this is possible. So abstracted, this is what I want:

I have a promise gotBanana, which resolves once I have gotten my banana.

this is in an async function called, getBananas(), which gets lots of bananas in the loop, it waits for the gotBanana promise to resolve every loop iteration.

I want to put this in another (probably async) function, but I want that function to await for the getBananas() function to finish.

Is it possible to do this or do i need to handle this situation in a different manner?

Upvotes: 0

Views: 130

Answers (1)

Tim Times
Tim Times

Reputation: 422

Maybe you're looking for Promise.all that resolves all promises in parallel and return promise when it will be done. So you just need to map all your assets (images or other) and await it.

Upvotes: 3

Related Questions