gpt4 book ai didi

javascript - javascript 中的 "Done"函数

转载 作者:行者123 更新时间:2023-11-30 12:19:05 24 4
gpt4 key购买 nike

例如,我阅读了关于创建任务的 Grunt 文档。在“Tasks can be asynchronous”部分,有一个“done”函数的用例,我想知道为什么我们需要它。

grunt.registerTask('asyncfoo', 'My "asyncfoo" task.', function() {
// Force task into async mode and grab a handle to the "done" function.
var done = this.async();
// Run some sync stuff.
grunt.log.writeln('Processing task...');
// And some async stuff.
setTimeout(function() {
grunt.log.writeln('All done!');
done();
}, 1000);
});

最佳答案

这是 Grunt 在执行异步工作时知道您的任务何时完成的唯一方法。

SO Post详细介绍了 JS 中异步的含义以及如何使用它。

基本上,setTimeout 会在 1 秒后调用您的回调函数。但是,grunt 不知道您的回调何时完成,因为 setTimeout 本身会在调用后立即返回。因此,done() 函数的存在是为了向您提供一种方法来告诉 grunt 您的任务已完成,无论何时。

关于javascript - javascript 中的 "Done"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31604311/

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