Search code examples
node.jsazureazure-node-sdk

wait() function for azure nodejs sdk


Is there a wait() function available for azure nodejs SDK just like what python SDK has. Below is my python code to start a VM in azure

async_vm_start = compute_client.virtual_machines.start(group_name, vm_name)
async_vm_start.wait()

So here my whole program waits till the VM completely spins up and proceeds. Below is my nodejs code to start a VM

clientCompute.virtualMachines.start(resourceGroupName, vmName, function(err, result) {
    if (err) console.log(err);
    else console.log(result);
})

Here my program don't wait and just proceeds further even though behind the scenes the VM is still in the process of starting.

I have tried setTimeout but it's not reliable. So is there any way for my nodejs function to wait till the VM completely start.

Thanks in advance


Solution

  • The third argument to the start() function is a callback function which will be called after the VM has been started. If you had the following code:

    console.log('I will be logged first!')
    clientCompute.virtualMachines.start(resourceGroupName, vmName, function(err, result) {
        console.log('I will be logged after the VM has started!')
    })
    console.log('I will be logged almost immediately after the first!')
    

    you would see the order that they will run. If there is anything that needs to happen after the VM has started, do it inside of that callback.

    Of course, it can be a pain if you have many things to do in order and you have a callback inside of a callback inside of a callback...it just gets messy. I'm not sure what version of the SDK you are using but with newer ones you could use async/await:

    console.log('I will be logged first!')
    await clientCompute.virtualMachines.start(resourceGroupName, vmName)
    console.log('I will be logged after the VM has started!')
    

    or use promisify to convert callback-based functions into promises which can be awaited.