如果它在里面使用另一个函数,那么函数定义会是什么样的--JavaScript

时间:2017-08-11 07:42:00

标签: javascript node.js function

我在enter image description here上找到了这段代码:

function dothings(things, ondone){
    function go(i){
        if (i >= things.length) {
            ondone();
        } else {
            dothing(things[i], function(result){
                return go(i+1);
            });
        }
    }
    go(0);
}

我无法弄清楚我应该如何定义dothing函数。应该是这样的:

function dothing(elem)
{
   //do things with elem
}

或者我应该以某种方式指出function(result),如果是,我应该怎么做?提前谢谢。

4 个答案:

答案 0 :(得分:1)

这样做,

function dothing(elem, cb)
{
   //do things with elem
   // return the result
   cb(...somedata)
}

答案 1 :(得分:1)

此处dothing是一个异步函数。

在异步函数签名中,回调是其中一个参数。

另外,为了从异步函数返回值,需要使用要返回的值调用回调。 返回语句在异步函数中没有意义。

定义可能如下:

function dothing(elem, callback){
     // Your logic to process elem
     // var result = some_custom_logic(elem);
     callback(result);
}

答案 2 :(得分:1)

您可以定义类似这样的内容

function dothing(elem, callback){
    //result =  do stuff with elem
    callback(result);
}

答案 3 :(得分:1)

它看起来有点过于复杂,因为它一遍又一遍地调用该函数,并且不适用于things的元素,并且以相反的顺序调用ondone函数。

function dothings(things, ondone) {
    function go(i) {
        if (i < things.length) {
            console.log(i, things[i]);
            go(i + 1);
            ondone(i);
        }
    }

    go(0);
}

dothings([1, 2, 3, 4], function (v) { console.log(v, 'done'); })
.as-console-wrapper { max-height: 100% !important; top: 0; }