简体   繁体   English

为什么功能即使在循环内被异步调用也依序运行?

[英]Why functionalities runs sequentially even though they are being called asynchronously inside a loop?

I am creating a wrapper function which will take array of functions and executes every function in a parallel manner so thought of using setTimeout but still functions are running sequentially. 我正在创建一个包装器函数,它将使用函数数组并以并行方式执行每个函数,因此考虑使用setTimeout,但函数仍按顺序运行。 I suspect it could be because of closure that is being used to call SetTimeout. 我怀疑可能是因为用于调用SetTimeout的闭包。 But why does it matter since setTimeout is async anyway? 但是,为什么setTimeout仍然是异步的,为什么这很重要?

// some blocking functionality
var withDelay = function (a) {
   var currentTime = new Date().getTime(), delay = 5000;
   while (currentTime + delay >= new Date().getTime()) {
   }
   console.log(a+"I am with delay");
}

// some non blocking functionality
var withoutDelay = function(a) {
   console.log(a+"I am with no delay");
}

var fnArr = [withDelay, withoutDelay]; //array of functions
var args = ["Hi,"]; // arbitrary params

for( var i=0; i < fnArr.length; i++) {
    var fn = fnArr[i];
    (function(f,arg) {
        return setTimeout(function(){ return f.apply(f,arg) },0);
    })(fn,args)
}

Expected output: 预期产量:

Hi,I am with no delay 嗨,我刻不容缓

Hi,I am with delay 嗨,我迟到了

but Actual output is: 但实际输出是:

Hi,I am with delay 嗨,我迟到了

Hi,I am with no delay 嗨,我刻不容缓

JS runs on a single thread, Your function will not run parallelly. JS在单个线程上运行,您的函数将不会并行运行。 It will only run one at a time. 一次只能运行一个。 Since you have scheduled both the functions with 0 delay as soon the first function from fnArr array viz. 由于您已将两个函数的延迟时间安排为0,因此fnArr数组fnArr的第一个函数将fnArr withDelay will run first. withDelay将首先运行。 Only when this will complete its execution, the second function withoutDelay will start its execution. 仅当这将完成其执行时,第二个没有withoutDelay的函数才会开始执行。 setTimeout will not guarantee your execution after provided interval, it is the minimum interval after which your function will execute. setTimeout将不能保证在提供的间隔后执行,这是函数执行的最小间隔。 You can read more about setTimeout here 您可以在此处阅读有关setTimeout更多信息

While loop doesnot delay a function you need to use setTimeout in your withDelay() and it working fine while循环不会延迟功能,您需要在withDelay()使用setTimeout并且它可以正常工作

 var withDelay = function (a) { setTimeout(() => {console.log(a+"I am with delay")},5000); } // some non blocking functionality var withoutDelay = function(a) { console.log(a+"I am with no delay"); } var fnArr = [withDelay, withoutDelay]; //array of functions var args = ["Hi,"]; // arbitrary params for( var i=0; i < fnArr.length; i++) { var fn = fnArr[i]; (function(f,arg) { return setTimeout(function(){ return f.apply(f,arg) },0); })(fn,args) } 
An example to call functions in a line after delay. 延迟后在一行中调用函数的示例。 As asked by questioner. 如发问者所问。

 function func1(){ console.log("Function 1 is executed"); console.timeEnd('t'); } function func2(){ console.log("Function 2 is executed"); console.timeEnd('t'); } function func3(){ console.log("Function 3 is executed"); console.timeEnd('t'); } let arrr = [ {func:func1,delay:2000}, {func:func2,delay:2000}, {func:func3,delay:3000}, ] async function callWithDelay(funcArr){ for(let func of funcArr){ //just to see time in console not necesarry console.time('t'); //create a promise let promise = new Promise((resolve,reject) => { //'promise' will resolve after the function inside following code will end setTimeout(()=> { resolve(); func.func(); },func.delay) }) //The code will not proceed until the 'promise' is resolved(func is excecuted); let x = await promise; } console.log("All the functions are excecuted"); } callWithDelay(arrr); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即使没有循环 Javascript 也会调用不间断查询 - Non stop queries being called even though there is no loop Javascript 即使其他代码运行,事件侦听器也不会在循环的最后一次迭代中被删除 - Event listener not being removed last iteration of a loop even though other code runs 为什么我的Backbone.js错误回调被调用,即使Rails应该返回成功响应? - Why is my Backbone.js error callback being called even though Rails is supposedly returning a success response? 为什么不按顺序调用 jQuery 函数? - Why aren't jQuery functions being called sequentially? 即使不满足条件,if语句中的Javascript函数仍然运行 - Javascript function inside if statement still runs even though condition is not met 为什么不会异步调用此回调 - Why is this callback not called asynchronously 为什么我的 for 循环中的异步代码没有按顺序运行? - why is my async code inside for loop not running sequentially? 为什么即使在 alert() 之前调用 preventDefault() 也会执行 alert()? - Why alert() executes even though preventDefault() is called before alert()? 为什么即使我从未调用过回调 function 也会被调用? - Why callback function gets called even though I never invoked? 为什么不应该进行这个ajax调用 - Why is this ajax call being made even though it shouldn't be
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM