I have a function which has two statements that are executed asynchronously.
const returnedPackage = await getAssetRegistry('es.test.Asset')
.then(function (assetRegistry) {
return assetRegistry.add(package);
});
await setEnclosingAsset(recoveredVals, assetInfoObj['assetId']);
return returnedPackage;
The first lambda performs the save but without finishing, the second statement is executed. In the second sentence, with the identifier. I perform a search for the value that is being saved in the statement above. And I say saving because it returns an exception saying that no value with that identifier has been found. So I imagine that both are executed in parallel.
I thought that maybe I was doing the save wrong but if I comment the line of the await setEnclosingAsset()...... The save does it correctly for me.
Any suggestions to solve this execution flow error?
EDIT
I tried the following but the error persists
await getAssetRegistry('es.test.Asset')
.then(function (assetRegistry) {
newPackage = assetRegistry.add(package);
})
.then(function () {
setEnclosingAsset(recoveredVals, assetInfoObj['assetId']);
});
According to the code that you leave as an example, the problem that you pose in my opinion has to do with the fact that you have at least 2 nested promises. To execute something when a promise ends, you can use the
await
or the del callback,.then()
but you have to do it with each promise, otherwise there will be an asynchronous part. I leave you a working example with nested promises, in this example only oneawait
is enough because both promises execute theresolve()
but it might not be like that. You could see when something is a promise or not doingconsole.log
'sIn the code of the second attempt you make, the second
then()
one is going to execute if the above is a promise, then maybe you should do something like:The reason this doesn't work for you is that JavaScript executes asynchronous streams "intelligently", meaning it only waits when it has to wait.
When you have code like this
Javascript doesn't wait, because it assumes getData and doWork are unrelated and launches them in parallel. This is because async functions are really nothing more than promises that fire and resolve themselves.
To force the wait, you must have code that uses the first function before the second function executes. For example:
Since you need the value of result in order to doWork, Javascript will wait to execute the second function.
In your code you do not use the value of returnedPackage in your code, so both are executed in parallel. If you do something like
The second function will not be launched until the first one is executed.