How do I write a blocking synchronous method in Javascript?

前端 未结 3 1385
情书的邮戳
情书的邮戳 2020-12-31 15:25

I\'m trying to mock out a method which takes a long time for testing purposes but can\'t find a good way to do this in Javascript. Any good approaches besides writing a very

3条回答
  •  心在旅途
    2020-12-31 15:34

    If you can use the newer await/await syntax:

    function sleep (time) {
      return new Promise((resolve) => setTimeout(resolve, time));
    }
    
    async function example() {
        await sleep(4000);
        return 1;
    }
    
    console.log(await example());
    

提交回复
热议问题