Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

javascript - 手动将功能插入Javascript / Nodejs事件队列?(Manually insert function to Javascript/Nodejs event queue?)

For example, if I want to do this

(例如,如果我想这样做)

function doA(callback) {
  console.log("Do A")
  callback()
}

function doB() {
  console.log("Do B")
}

function doC() {
  console.log("Do C")
}

doA(doC)
doB()

I want the output of

(我想要的输出)

Do A
Do B
Do C

However, the only way to get this result would to use this hack to push item to the queue:

(但是,获得此结果的唯一方法是使用此技巧将项目推送到队列:)

  setTimeout(() => {
    doTask();
  }, 0);

Is there a way to manually add an item to the javscript/nodejs event queue?

(有没有办法手动将项目添加到javscript / nodejs事件队列?)

I'm asking this more for theoretical exercise rather than any practical programming needs.

(我要的是理论练习,而不是任何实际的编程需求。)

It seems like there is no way to do any async task without first invoking built-in functions that is already async.

(在没有先调用已经异步的内置函数的情况下,似乎无法执行任何异步任务。)

  ask by user2727691 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

setTimeout works fine, I don't consider it a hack.

(setTimeout工作正常,我不认为这是一个hack。)

But there's also queueMicrotask , which might sound more suited to your purpose - it queues a microtask which'll run as soon as all other synchronous Javascript has finished executing:

(但是还有一个queueMicrotask ,听起来可能更适合您的目的-它将一个微任务排队,该微任务将在所有其他同步Javascript完成执行后立即运行:)

 function doA(callback) { console.log("Do A") queueMicrotask(callback); } function doB() { console.log("Do B") } function doC() { console.log("Do C") } doA(doC) doB() 

It's basically equivalent to Promise.resolve().then(callback) .

(它基本上等效于Promise.resolve().then(callback) 。)

Note that an immediate setTimeout queues a macrotask (one which will run once the event loop gets around to processing the next message , which may take a few milliseconds) - in contrast, queueMicrotask and Promise.resolve.then queues a microtask, which will run basically immediately after other synchronous JS is finished.

(请注意,立即setTimeout一个宏任务排队(该宏任务将在事件循环处理下一条消息时运行 ,该任务可能需要几毫秒的时间)-与此相反, queueMicrotaskPromise.resolve.then将一个微Promise.resolve.then排队,该宏将运行基本上在其他同步JS完成后立即执行 。)

Also keep in mind that queueMicrotask , while supported in Node, is not exactly widely supported in browsers yet, so if you want to use it on a public-facing website, make sure to include a polyfill (or use the Promise.resolve method).

(另外请记住,虽然queueMicrotask支持的queueMicrotask尚未在浏览器中得到完全支持,所以如果要在面向公众的网站上使用它,请确保包含Promise.resolve (或使用Promise.resolve方法) 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...