Javascript - make 函数在函数完成时告诉调用者

Javascript - make function tell the caller when function is finished

本文关键字:函数 调用者 完成时 make Javascript      更新时间:2023-09-26

假设我正在调用一个这样的函数:

some_function('pages',{attr1: 1, attr2: 2},function(){
    alert('the function is ready!');
}

现在如何设置"some_function()"函数以返回到调用方它已准备就绪并使警报响起?

谢谢:)

我想你的意思是回调。也许是这样的:

function some_function(param1, param2, callback) {
    // normal code here...
    if ( typeof callback === 'function' ) { // make sure it is a function or it will throw an error
        callback();
    }
}

用法:

some_function("hi", "hello", function () {
    alert("Done!");
}); 
/* This will do whatever your function needs to do and then,
when it is finished, alert "Done!" */

注意:return放在if子句之后。

你的意思是这样吗?

function some_function(type, options, callback) {
  if (some_condition) {
    callback();
  }
}

假设some_function的签名如下所示:

function some_function(name, data, callback)

您只需要在准备好时致电callback即可。

function some_function(name, data, callback){
    // do whatever
    if(typeof callback === 'function'){
        callback(); // call when ready
    }
}