Not really complex, you just need to time it properly.
First off, you cannot upload files without providing a folderid. Hence you need to create a folder first and then pass that ID to the file upload. Simply create the folder first and wait for the completion.
Secondly, your file upload has the same issue. As explained multiple times on this forum, the API will return you the asset id immediately, though that doesn't mean the file is in the system as it might take a longer time to create renditions, apply workflow, and so forth.
You can also enable the duplicate file check which will not add the file and then you can rename it locally and re-upload. Though, file check is done with the md5 hash, so just renaming the file won't do it.
Hope this helps.