I’m new to Node.js and was trying to get a lease from azure blob.
const leaseID = await acquireLease(container,blobName); const result = await download(blob);
and acquireLease method is
const acquireLease = async function(container,blobName){ var leaseID; blobService.acquireLease(container,blobName ,function(error,result,response){ if(!error) { // Got lease leaseID = result.id; } }) return(leaseID); } exports.acquireLease = acquireLease;
but before the acquireLease method gets completed and leaseID is got, the next main method
const result = await download(blob);
gets executed.
I tried promises but couldn’t succeed.
const acquireLease = async function(container,blobName){ var leaseID; return new Promise((resolve,reject)=>{ blobSvc.acquireLease(container,blobName ,function(error,result,response){ if(!error) { // Got lease leaseID = result.id; } }) resolve(leaseID); }) } exports.acquireLease = acquireLease;
Any suggestions or help appreciated.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You were really close with your Promise version! You just need to call resolve
and reject
at the right times.
Presumably, if error
is truthy, then you should reject. Otherwise, it’s safe to assume your result is valid and you can resolve the promise with result.id
. There is no need for a leaseID
variable. Also, if the function just returns a Promise, there’s no need to mark it async.
const acquireLease = function (container, blobName) { return new Promise((resolve, reject) => { blobSvc.acquireLease(container, blobName, function (error, result, response) { if (error) { reject(error) } else { resolve(result.id) } }) }) } exports.acquireLease = acquireLease;
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0