sid597
sid597

Reputation: 1019

how do I make my code synchronus in javascript

I want to make my code synchronus, I am used to python but now trying to do testing things in protractor and some code uses javascript, here things fall apart following is my code :

describe('screenshot take', () => { 

    var listLength = urlList.length

      for (let i = 0; i < listLength; i++) {
         it('screenshot taken', () => {
          console.log("0")

          TakeScreenshot(  urlList[i],i)  
         console.log("1")

         });
    }
});



function  TakeScreenshot(url,rank){
    console.log("2")

    browser.get(url)
    console.log("3")

    browser.takeScreenshot().then((png) =>{
       console.log("4")
       var stream =  createWriteStream( ImagePath+'.png');  
       stream.write(Buffer.from(png, 'base64'));
       stream.end; 
      console.log("5")


     }); 

}

When try look into my console I get the following Output

0
2
3
1
4
5

But I want it to be

    0
    2
    3
    4
    5
    1

I have tried using .then() and browser.sleep() but I am not able to gt it I tried reading through async/await but I don't know how to use it. So can someone help me out with this

Upvotes: 0

Views: 127

Answers (1)

Einar &#211;lafsson
Einar &#211;lafsson

Reputation: 3177

When using an async function you need to use await on other asynchronous functions to make rest of the code wait for their response.

describe('screenshot take', async () => { 

    var listLength = urlList.length

      for (let i = 0; i < listLength; i++) {
         it('screenshot taken', () => {

          console.log("0")

          await TakeScreenshot(  urlList[i],i)  

          console.log("1")

         });
    }
});



const TakeScreenshot = async (url,rank){
    console.log("2")

    browser.get(url)

    console.log("3")

    const png = await browser.takeScreenshot()

    console.log("4")

    var stream =  createWriteStream( ImagePath+'.png');  
    stream.write(Buffer.from(png, 'base64'));
    stream.end; 

    console.log("5")

}

Be aware though that using for loops in async functions is not recommended. You can see more information on why here https://eslint.org/docs/rules/no-await-in-loop

Upvotes: 2

Related Questions