使用回调编写函数

时间:2016-11-07 00:57:42

标签: javascript

让我们想象一下我有一些代码:

var someString = "";
function do1(){
    doA();
    doB();
}

function doA(){
    // some process that takes time and gets me a value
    someString = // the value I got in prior line

function doB(){
    //do something with someString;
}

确保doB尝试使用它定义somestring的正确方法是什么?我认为这是一种需要回调的情况,但我不确定如何设置它?

3 个答案:

答案 0 :(得分:1)

通常,我已经像回调参数一样解决了这个问题。但是,我不知道这是正确的答案。就我而言,它做得很好。

var someString = "";
function do1(){ 
    doA(doB);
}

function doA(callback){
    // some process that takes time and gets me a value
    someString = // the value I got in prior line
    callback();
}

function doB(){
    //do something with someString;
}

答案 1 :(得分:0)

我经常编写这些函数,以便可以使用或不使用回调函数调用该函数。您只能在callback时调用typeof callback === 'function'函数来执行此操作。这允许包括回调可能性的功能更加通用。显然,对callback()的调用需要来自您正在执行的任何异步操作的回调。在下面的示例中,setTimeout用作异步操作。

var someString = "";
 
function do1() {
    doA(doB); //Call doA with doB as a callback.
}
 
function doA(callback) {
    setTimeout(function() {
        //setTimeout is an example of some asynchronous process that takes time
        //Change someString to a value which we "received" in this asynchronous call.
        someString = 'Timeout expired';
        //Do other processing that is normal for doA here.

        //Call the callback function, if one was passed to this function
        if (typeof callback === 'function') {
            callback();
        }
    }, 2000);
}
 
function doB() {
    //do something with someString;
    console.log(someString);
}

do1();

当然,您可以在不使用全局变量的情况下执行此操作:

function do1() {
    doA(doB); //Call doA with doB as a callback.
}
 
function doA(callback) {
    setTimeout(function() {
        //setTimeout is an example of some asynchronous process that takes time
        //Simulate a result
        var result = 'Timeout expired'; 

        //Do other processing that is normal for doA here.

        //Call the callback function, if one was passed to this function
        if (typeof callback === 'function') {
            callback(result);
        }
    }, 2000);
}
 
function doB(result) {
    console.log(result);
}

do1();

答案 2 :(得分:0)

function someFunctionA(callback){
  var someString = "modify me";
  callback(someString);
}

function someFunctionB(someString){
  // do something
}

function main() {
   someFunctionA(somefunctionB);
 }