Trying to download a pdf file in google chrome browser. The script currently successfully opens up the tab displaying the pdf. But script is flaky while opening a new tab

Synthetics question template

Trying to download a pdf file in google chrome browser using the synthetic script. The script currently successfully opens up the second tab and switch to another tab as well and displays the pdf. But script is flaky while opening a second tab. Sometimes it passes successfully. But most of the times it tends to fail. I tried giving a browser.sleep function as well. But still facing problem.
Code looks like:

.then(function(){
console.log(“Click on Sample Check”);
return $browser.waitForAndFindElement($driver.By.xpath("//button[text()=‘View Sample Check’]"),20000).then(function(element){
element.click();
})
}).then(function(){
return $browser.sleep(80000);
}).then(function(){
return $browser.getAllWindowHandles().then(function(handles){
$browser.sleep(10000)
return $browser.switchTo().window(handles[1])
//return $browser.sleep(2000);
})
})

I am facing frequent failures at the step :
return $browser.getAllWindowHandles().then(function(handles) - looks like it does not return the second tab itself. Because of that the step at:
return $browser.switchTo().window(handles[1]) does not take the argument (handles[1]) at all.

error: Error: invalid argument: ‘name’ must be a string

Please help me on this one.