I call a function and want to put the result value in variable but it does not happen. can you tell me why? main function:
var encryptedPassword; encrypt(websiteCredentials.password,getStorageItem('masterpass')).then(concatenated => encryptedPassword = concatenated); websiteCredentials.password = encryptedPassword; console.log('credentials was hit', websiteCredentials.password);
When I print it out it shows null. Can you please tell me why?
async function encrypt(password, masterpass) { .... return concatenated; }
Advertisement
Answer
Ah, the reason is because the encrypt function is asynchronous, meaning it takes time to execute. As a result, your code will start it when it’s called, but then move onto the next lines without waiting for it to finish. Try adding “await” before encrypt is called, it makes it so that the code will wait until it’s done, and if that doesn’t work, try putting await before some of the parameters too.