gpt4 book ai didi

javascript - 回调函数抛出错误

转载 作者:行者123 更新时间:2023-11-29 18:49:15 25 4
gpt4 key购买 nike

我正在尝试解决这个异步问题。我解决了问题。

但是,在调用“完成”回调后,它会抛出一个错误。我不知道为什么。

问题:

I want to print the task number once "Done" is invoked. But it throws an error saying TypeError: "callback" argument must be a function

问题:

A "TaskRunner" Constructor takes one argument, "concurrency", and exposes one method "push" on its prototype. The "push" method takes one argument "task" which is a "function"

Passing a task to a push method of a TaskRunner instance should immediately execute (call/run/invoke) the task, unless the number of currently running tasks exceeds the concurrency limit.

function TaskRunner(concurrency) {
this.count = concurrency;
this.queue = [];
}

TaskRunner.prototype.push = function(task) {
if (this.count === 0) {
this.queue.push(task);
} else {
this.invoke(task);
}
}

TaskRunner.prototype.invoke = function(task) {
task.call(null, this.done.bind(this));
this.count--;
}

TaskRunner.prototype.done = function(num) {
console.log(`After Executing done: ${num}`)
this.count++;
this.execute();
}

TaskRunner.prototype.execute = function() {
if (this.queue.length > 0) {
var task = this.queue.shift();
this.invoke(task);
}
}

function factory(num) {
return function exampleSimpleTask(done) {
this.num = num;
console.log("task", "Before " + new Date().getTime());
setTimeout(done(num), 2000);
}
}


var r = new TaskRunner(2);

r.push(factory(1));
r.push(factory(2));
r.push(factory(3));

编辑:出于某种原因,在 jsfiddle 上它运行良好,但是当我在本地运行相同的代码时它失败了。

请帮忙。

最佳答案

您将函数的结果传递给setTimeout:

setTimeout(done(num), 2000);

这将立即调用 done(num) 并且 setTimeout 将尝试调用返回的任何 done() ,因为它是一个函数。

你应该给它传递一个它可以调用的函数:

setTimeout(() => done(num), 2000);

或者[正如@JaromandaX 在评论中指出的那样] 你可以利用 setTimeOut 的选项第三个参数,它将被传递到回调函数中:

setTimeout(done, 2000, num);

这将调用函数done 并传入num

关于javascript - 回调函数抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51904368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com