JavaScript多回调函数

Rob*_*Rob 16 javascript callback

我一直试图在Javascript中找出回调函数功能一段时间没有任何成功.我可能有代码乱了,但我没有得到任何Javascript错误,所以我认为语法有点正确.

基本上,我正在寻找getDistanceWithLatLong()函数在updateDB()开始之前结束,然后确保在printList()函数开始之前结束.

我让它在函数上使用硬编码的"setTimeout"调用,但是我过度补偿并迫使用户等待更长时间而不需要Callback的东西.

有什么建议?以下是代码:

function runSearchInOrder(callback) {
    getDistanceWithLatLong(function() {
        updateDB(function() {
            printList(callback);
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*bot 24

要实现此目的,您需要将下一个回调传递给每个函数.

function printList(callback) {
  // do your printList work
  console.log('printList is done');
  callback();
}

function updateDB(callback) {
  // do your updateDB work
  console.log('updateDB is done');
  callback()
}

function getDistanceWithLatLong(callback) {
  // do your getDistanceWithLatLong work
  console.log('getDistanceWithLatLong is done');
  callback();
}

function runSearchInOrder(callback) {
    getDistanceWithLatLong(function() {
        updateDB(function() {
            printList(callback);
        });
    });
}

runSearchInOrder(function(){console.log('finished')});
Run Code Online (Sandbox Code Playgroud)

此代码输出:

getDistanceWithLatLong is done
updateDB is done
printList is done
finished 
Run Code Online (Sandbox Code Playgroud)

  • 将变量从一个回调传递到另一个回调怎么办? (6认同)