【问题标题】:Javascript Callbacks to Output in OrderJavascript 回调按顺序输出
【发布时间】:2021-07-17 21:47:11
【问题描述】:

这些函数的输出以正确的顺序调用为 2、3、1,但我喜欢它先输出为 1,然后是 2、3。

const firstFunction = () => {
  setTimeout(function() {
    console.log(1);
  }, 3000);
}

const secondFunction = () => {
  console.log(2);
}

const thirdFunction = () => {
  console.log(3);
}

firstFunction();
secondFunction();
thirdFunction();

我尝试使用回调,执行 1 后没有输出 2、3。

const firstFunction = () => {
  setTimeout(function() {
    console.log(1);
  }, 3000);
}

const secondFunction = (callback) => {
  console.log(2);
  callback();
}

const thirdFunction = (callback) => {
  console.log(3);
  callback();
}

firstFunction(function() {
  secondFunction(function() {
    thirdFunction();
  });
});

如何使用回调实现这一点?

【问题讨论】:

    标签: javascript asynchronous callback


    【解决方案1】:

    firstFunction 是第一个应该有回调的函数。而且,你有什么理由在 firstFunction 中设置超时?

    const firstFunction = (callback) => {
      setTimeout(function() {
        console.log(1);
        callback();
      }, 3000);
    }
    
    const secondFunction = () => {
      console.log(2);
    }
    
    const thirdFunction = () => {
      console.log(3);
    }
    
    firstFunction(function() {
      secondFunction();
      thirdFunction();
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多