同步while循环javascript

时间:2019-04-13 12:40:26

标签: javascript while-loop callback synchronous

我想要此输出1,1,1,....

而不是2,1

我想同步运行

//just wait 2 seconds
function s(callback){
    setTimeout(() => {
        callback()
    }, 2000);
}
a=[2]
while (a.length!==0){
    a.shift()
    s(()=>{
        a.push(2)
        console.log('1');
    })
}
console.log('2');

1 个答案:

答案 0 :(得分:2)

使用当前代码,实现此目标的一种方法是使用async/await和Promises。

//just wait 2 seconds
function s(callback) {
  return new Promise(resolve => {
    setTimeout(() => {
      callback()
      resolve()
    }, 2000);
  })
}

const main = async function() {
  const a = [2];
  while (a.length !== 0) {
    a.shift()
    // This "waits" for s to complete. And s returns a Promise which completes after 2 secs
    await s(() => {
      a.push(2)
      console.log('1');
    })
  }
  console.log('2');
}

main()

如果您真的只需要无限循环while(true) { /* ... */ }就足够了。