在调用下一个函数之前,如何等待一个函数完成呢

How can one wait for a function to complete before the next function is called?

本文关键字:函数 调用 一个 等待 何等待 下一个      更新时间:2023-09-26

在调用下一个函数之前,等待函数完成的最佳方式是什么?

我有一个场景,其中连续调用两个函数,一个接一个。我需要在调用第二个之前完成第一个。

Function1();   
Function2();   

如何告诉代码在尝试Function2之前等待Function1完成?

WebDevelopment:解决方案可以是javascript或jQuery,也可以是基于Ajax的。

谢谢。。。

你可以做很多方法,但一个非常简单的例子

function first(){

// define every thing here and then at the end call your second function

function2();

}

点击此处查看更多可能性

您可以使用Promisecallback来解决此问题,Promises是更现代、更干净的做事方式:

承诺:

function foo() {
   return new Promise(function(resolve, reject) {
      // do some work
      resolve(optionalParam);
      // something caused an error whoops
      reject(optionalParam);
   })
}
function bar() {
    // do something
};
// Call bar only once foo finishes
foo().then(function() {
   bar();
}, function() {
   // this is the reject case an error here
});

Promise可以被链接,这意味着如果bar是Promise,我们可以将另一个then事件链接到它。

你也可以使用回调来解决你的问题

function foo(cb) {
   var data = 'alex';
   cb(data);
}
function bar(name) {
   // some processing
   console.log(name);
}
// Call foo, then execute bar when foo finishes
foo(function(data) {
    bar(data);  // alex would be logged once the callback fires
});

在这里的回调示例中,我们传递一个函数作为参数,一旦运行的函数块遇到您对cb参数的调用,它将调用模拟异步的函数。请记住,它不会停止该函数的执行上下文。如果我们有这样的代码:

function foo(cb) {
    var data = 'alex';
    cb(data);
    console.log('this is after so don't print it'); <-- still prints
};

当回调在事件队列上完成时,最终的console.log将打印出来(当然,除非您触发一个类似于http请求的even-in-CB,在该请求中,日志将触发,然后http请求将在之后完成)。

要停止最后一个控制台日志,您需要明确地告诉javascript在调用cb时返回,以防止该方法中的进一步执行,就我个人而言,这就是我喜欢Promises的地方,一旦您解析或拒绝promise,该函数范围内的执行上下文就会停止。

如果你在浏览器中,只需使用回调,这是最简单的跨浏览器方法。

示例:

function sayBill() {
   console.log('bill');
}
function sayHiAfterTwoSeconds(callback) {
  setTimeout(function() {
     console.log('hi');
     // call the function you passed in parameter
     if (typeof callback === 'function') {
        callback();
     }
  });
}
sayHiAfterTwoSeconds(sayBill);
// will output 'bill hi'

https://jsfiddle.net/80bbbjco/

如果你想要更好的方式,但不是跨浏览器,那么有承诺:https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise

或者更现代但不受支持的ATM异步等待:https://jakearchibald.com/2014/es7-async-functions/