简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM