简体   繁体   English

似乎无法让 JavaScript 同步运行

[英]Can't seem to get JavaScript to run in synchronous

I have a few functions that need to be performed in order and JavaScript tends to do them asynchronous.我有一些功能需要按顺序执行,JavaScript 倾向于异步执行它们。 I've looked into various methods of solving this problem including using callbacks, creating my own promise, a Promise.all() technique, and finally a newer version using async functions and await.我研究了解决这个问题的各种方法,包括使用回调、创建我自己的 promise、Promise.all() 技术,最后是使用异步函数和等待的更新版本。 I still wasn't able to get the code to run the way I wanted to.我仍然无法让代码按照我想要的方式运行。

The idea is, run initialize() first, initialize calls colorcells, and finally last thing to run is draw_path.这个想法是,首先运行initialize(),initialize调用colorcells,最后运行的是draw_path。

function initialize() {   
 for (let i = 1; i < 20; i++) {
     setTimeout(() => {
       colorcells(i)
     }, i * 30)}
}
    
function colorcells (cell){
  // then execute this function from initialize
}
        
function draw_path(){
   // this should be the last function to get executed
}

async function init(){
     await initialize()
     draw_path()
 }

// starts our code
init()

You could use promise, but it would make more sense to code a "queue" and when it is done, you call the next step.您可以使用 promise,但编写“队列”代码更有意义,完成后,您调用下一步。

 const max = 20; let current = 1; function colorNext() { colorCell(current); current++; if (current < max) { window.setTimeout(colorNext, 30); } else { drawPath(); } } function colorCell(cell) { console.log("Color", cell); } function drawPath() { console.log('draw called'); } colorNext();

It can be done with promises, but there is no need to read all those timeouts.可以通过 Promise 完成,但无需阅读所有这些超时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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