简体   繁体   English

JavaScript 带有回调/闭包的控制台写入任务?

[英]JavaScript console writing task with callbacks/ closures?

I'm working on a JavaScript task where I need to print to the console different instructions after a certain amount of time has passed.我正在处理 JavaScript 任务,我需要在经过一定时间后向控制台打印不同的指令。 The task is to make and serve sandwiches.任务是制作和供应三明治。 A sandwich takes 1 minute to make, and 30 seconds to serve.制作一个三明治需要 1 分钟,上桌需要 30 秒。

The function needs to take the number of sandwiches that are requested and print in an order like "Make Sandwich 1, Serve Sandwich 1, Make Sandwich 2, Serve Sandwich 2" etc function 需要获取请求的三明治数量并按“制作三明治 1、上三明治 1、制作三明治 2、上三明治 2”等顺序打印

This is what I have so far, but it's not working correctly and I'm not sure how to fix it.到目前为止,这是我所拥有的,但它无法正常工作,我不确定如何修复它。

function makeSandwich(num, callback) {
  for (let i = 0; i < num; i++) {
    console.log("Make Sandwich " + i);
    setTimeout(() => {
      callback(i);
    }, 6000);
  }
}

function serveSandwich(num) {
    setTimeout(() => {
    console.log("Serve sandwich " + num);
  }, 3000);
}

makeSandwich(2, serveSandwich); //this does make, make, serve, serve

JavaScript setTimeout callbacks are asynchronous, so when you use it, the rest of the code keeps running. JavaScript setTimeout回调是异步的,所以当你使用它时,代码的 rest 一直在运行。

When you call makeSandwich , this is what happens:当您调用makeSandwich时,会发生以下情况:

  • First loop第一个循环
    • log to console: "Make sandwich 0"记录到控制台:“制作三明治 0”
    • start setTimeout timer (A), the passed function will run in 6 seconds启动setTimeout定时器(A),传递的 function 将在 6 秒后运行
    • end loop结束循环
  • Second loop第二个循环
    • log to console: "Make sandwich 1"登录到控制台:“制作三明治 1”
    • start second setTimeout timer (B)启动第二个setTimeout计时器 (B)
    • end loop结束循环
  • First timer (A) completes第一个计时器 (A) 完成
    • callback(0) is called回调(0)被调用
    • start setTimeout timer (C) for serving sandwich 1为三明治 1 启动setTimeout计时器 (C)
  • Second timer (B) competes第二计时器 (B) 比赛
    • callback(1) is called回调(1)被调用
    • start setTimeout timer (D) for serving sandwich 2为三明治 2 启动setTimeout计时器 (D)
  • Third timer (C) completes第三个计时器 (C) 完成
    • log to console: "Serve sandwich 0"记录到控制台:“服务三明治 0”
  • Fourth timer (D) completes第四个计时器 (D) 完成
    • log to console: "Serve sandwich 1"登录到控制台:“服务三明治 1”

If you want the functions to be run sequentially, you can use recursive callbacks.如果您希望函数按顺序运行,您可以使用递归回调。

// Make the sandwiches one by one, waiting each to complete before working on the next one
function makeSandwich(num, callback, i = 1) {
  console.log("Make Sandwich " + i);
  setTimeout(() => {
    // Pass a callback to the callback that will trigger when serving is complete
    callback(i, () => {
      // If there are still sandwiches left to make, start the next one
      if (i < num) {
        // This is the recusive part, the function calls itself to trigger the next loop 
        makeSandwich(num, callback, ++i);
      }
    });
  }, 6000);
}

function serveSandwich(num, callback) {
  console.log("Serve sandwich " + num);
  // This callback will let us know when serving is complete
  setTimeout(() => callback(), 3000);
}

makeSandwich(2, serveSandwich);

You can create a little delay function using a promise , and async/await to execute the food order.您可以使用 promise 创建一个小delay promise ,并使用async/await来执行食品订单。

 // Takes a number in milliseconds function delay(n) { return new Promise(res => { setTimeout(() => res(), n); }); } // Now iterate, log the result, // and delay for `n` milliseconds async function makeOrder(num) { for (let i = 0; i < num; i++) { console.log(`Make sandwich ${i + 1}`); await delay(2000); console.log(`Serve sandwich ${i + 1}`); await delay(1000); } } makeOrder(2);

Is this what you ment?这是你的意思吗?

function makeSandwichNew(num, callback) {
    if (num==0) console.log('Order \'Making\' Ready')
    else
    {
      console.log("Make Sandwich " + num);
      setTimeout(() => {
        console.log('sandwitch ' + num + ' ready')
        makeSandwichNew(num-1, callback)
        callback(num);
      }, 6000);
    }
}

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

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