জাভাস্ক্রিপ্টে চক্রের জন্য অ্যাসিঙ্ক্রোনাস


87

আমার একটি লুপ দরকার যা চালিয়ে যাওয়ার আগে অ্যাসিঙ্ক কলের জন্য অপেক্ষা করে। কিছুটা এইরকম:

for ( /* ... */ ) {

  someFunction(param1, praram2, function(result) {

    // Okay, for cycle could continue

  })

}

alert("For cycle ended");

আমি এই কিভাবে করতে পারে? তোমার কোন ধারনা আছে?


128
বাহ ( /* ... */ )দানবের মত রূপ এবং আমি এখন ভয় করছি :(
সূচালো

উত্তর:


182

আপনি জাভাস্ক্রিপ্টে সিঙ্ক্রোনাস এবং অ্যাসিঙ্ক্রোনাস মিশ্রিত করতে পারবেন না যদি আপনি স্ক্রিপ্টটি অবরুদ্ধ করেন, আপনি ব্রাউজারটিকে অবরুদ্ধ করুন।

আপনাকে এখানে পুরো ইভেন্ট চালিত পথে যেতে হবে, ভাগ্যক্রমে আমরা কুরুচিপূর্ণ জিনিসগুলি লুকিয়ে রাখতে পারি।

সম্পাদনা: কোড আপডেট হয়েছে।

function asyncLoop(iterations, func, callback) {
    var index = 0;
    var done = false;
    var loop = {
        next: function() {
            if (done) {
                return;
            }

            if (index < iterations) {
                index++;
                func(loop);

            } else {
                done = true;
                callback();
            }
        },

        iteration: function() {
            return index - 1;
        },

        break: function() {
            done = true;
            callback();
        }
    };
    loop.next();
    return loop;
}

এটি আমাদের একটি অ্যাসিনক্রোনাস সরবরাহ করবে loop, আপনি অবশ্যই এটি আরও আরও সংশোধন করতে পারেন উদাহরণস্বরূপ লুপের অবস্থা পরীক্ষা করার জন্য কোনও ফাংশন ইত্যাদি take

এখন পরীক্ষায়:

function someFunction(a, b, callback) {
    console.log('Hey doing some stuff!');
    callback();
}

asyncLoop(10, function(loop) {
    someFunction(1, 2, function(result) {

        // log the iteration
        console.log(loop.iteration());

        // Okay, for cycle could continue
        loop.next();
    })},
    function(){console.log('cycle ended')}
);

এবং আউটপুট:

Hey doing some stuff!
0
Hey doing some stuff!
1
Hey doing some stuff!
2
Hey doing some stuff!
3
Hey doing some stuff!
4
Hey doing some stuff!
5
Hey doing some stuff!
6
Hey doing some stuff!
7
Hey doing some stuff!
8
Hey doing some stuff!
9
cycle ended

28
হয়তো আমি কিছু মিস করছি, তবে আসলে এটি কীভাবে অ্যাসিক্রোনাস হয় তা আমি বুঝতে পারি না। আপনার কি সেটটাইমআউট বা অন্য কিছু দরকার নেই? আমি আপনার কোডটি চেষ্টা করেছিলাম, কনসোল.লগ বের করে দিয়েছি এবং গণনাটি প্রচুর পরিমাণে সরিয়ে নিয়েছি এবং এটি কেবল ব্রাউজারকে হিমশীতল করে তোলে।
রকেটসারেস্ট

আমি বিভ্রান্ত করছি কি loop.break()করা মানে? আপনি চাইলে কি এক উপায়?
হোয়াইটফিন

4
রকেটসারেফ্ট যেমন উপরে বলেছে, এই উত্তরটি তাত্পর্যপূর্ণ নয় এবং তাই সম্পূর্ণ ভুল!
kofifus

loop.next এর মতো, loop.break টি করা উচিত যখন এটি সত্য হয়: `ব্রেক: ফাংশন () {if (!) {সম্পন্ন = সত্য; কলব্যাক (); }} `
ডিবি-ইনফ

4
দুঃখিত, এটি আসলে অ্যাসিঙ্ক না হওয়ার কারণে তাকে হ্রাস করতে হয়েছিল।
রিকেলাস

44

আমি এটিকে সরল করে তুলেছি:

ফাংশন:

var asyncLoop = function(o){
    var i=-1;

    var loop = function(){
        i++;
        if(i==o.length){o.callback(); return;}
        o.functionToLoop(loop, i);
    } 
    loop();//init
}

ব্যবহার:

asyncLoop({
    length : 5,
    functionToLoop : function(loop, i){
        setTimeout(function(){
            document.write('Iteration ' + i + ' <br>');
            loop();
        },1000);
    },
    callback : function(){
        document.write('All done!');
    }    
});

উদাহরণ: http://jsfiddle.net/NXTv7/8/


+1 আমি এর অনুরূপ কিছু করেছি, তবে আমি সেটটাইমআউট অংশটি লাইব্রেরির ফাংশনে রেখেছি।
রকেটসারেস্ট

মূলত একটি পুনরাবৃত্তি হয় না?
পাভেল

7

@ আইভো যা পরামর্শ দিয়েছে তার একটি ক্লিনারের বিকল্প হ'ল একটি অ্যাসিনক্রোনাস মেথড ক্যু , ধরে নেওয়া এই যে সংগ্রহের জন্য আপনাকে কেবল একটি অ্যাসিঙ্ক কল করতে হবে।

( আরও বিশদ ব্যাখ্যার জন্য ডাস্টিন ডিয়াজের এই পোস্টটি দেখুন )

function Queue() {
  this._methods = [];
  this._response = null;
  this._flushed = false;
}

(function(Q){

  Q.add = function (fn) {
    if (this._flushed) fn(this._response);
    else this._methods.push(fn);
  }

  Q.flush = function (response) {
    if (this._flushed) return;
    this._response = response;
    while (this._methods[0]) {
      this._methods.shift()(response);
    }
    this._flushed = true;
  }

})(Queue.prototype);

আপনি কেবল একটি নতুন উদাহরণ তৈরি করেন Queue, আপনার প্রয়োজনীয় কলব্যাকগুলি যুক্ত করুন এবং তারপরে অ্যাসিঙ্ক প্রতিক্রিয়াটি দিয়ে সারিটি ফ্লাশ করুন।

var queue = new Queue();

queue.add(function(results){
  for (var result in results) {
    // normal loop operation here
  }
});

someFunction(param1, param2, function(results) {
  queue.flush(results);
}

এই প্যাটার্নের একটি অতিরিক্ত সুবিধা হ'ল আপনি কেবল একটির পরিবর্তে কাতারে একাধিক ফাংশন যুক্ত করতে পারেন।

যদি আপনার কাছে কোনও অবজেক্ট থাকে যার মধ্যে পুনরাবৃত্তকারী ফাংশন রয়েছে, আপনি দৃশ্যের পিছনে এই সারিটির জন্য সমর্থন যুক্ত করতে পারেন এবং কোডটি লিখেছেন যা সংলগ্ন দেখায়, তবে তা নয়:

MyClass.each(function(result){ ... })

eachবেনামে ফাংশনটি তাৎক্ষণিকভাবে সম্পাদন করার পরিবর্তে কাতারে রাখার জন্য লিখুন এবং তারপরে আপনার অ্যাসিঙ্ক কলটি সম্পূর্ণ হয়ে গেলে সারিটি ফ্লাশ করুন। এটি একটি খুব সাধারণ এবং শক্তিশালী ডিজাইনের প্যাটার্ন।

পিএস যদি আপনি jQuery ব্যবহার করেন তবে আপনার কাছে jQuery.Deferred নামক নিষ্পত্তি হিসাবে ইতিমধ্যে একটি অ্যাসিঙ্ক পদ্ধতির সারি রয়েছে ।


4
ঠিক আছে যদি প্রশ্নটি সঠিকভাবে বুঝতে পারে তবে এটি পছন্দসই আচরণ করবে না, মনে হচ্ছে তিনি কিছু কলব্যাক করতে চান যাতে someFunctionবাকী লুপটি বিলম্বিত করে, আপনার প্যাটার্নটি ফাংশনগুলির একটি তালিকা প্রস্তুত করে যা ক্রম সম্পাদন হবে এবং সমস্ত প্রাপ্ত হবে ফলাফল এক অন্য ফাংশন কল। এটি একটি ভাল প্যাটার্ন তবে আমি মনে করি না এটি প্রশ্নযুক্ত প্রশ্নের সাথে মেলে।
আইভো ওয়েটজেল

@ আইভো আরও তথ্য ব্যতীত আমরা নিশ্চিতভাবে জানতে পারি না, তবে সাধারণীদের সাথে কথা বলে আমি মনে করি যে সিঙ্ক্রোনাস কোডটি চালিয়ে যাওয়ার আগে অ্যাসিঙ্ক অপারেশনটির জন্য অপেক্ষা করা করা খারাপ নকশা; প্রতিটি ক্ষেত্রেই আমি এটি চেষ্টা করেছি, জেএস একক থ্রেড হওয়ার কারণে এটি লক্ষণীয় UI পিছিয়ে যায়। যদি অপারেশনটি খুব বেশি সময় নেয় তবে আপনি আপনার স্ক্রিপ্টটি ব্রাউজার দ্বারা জোর করে বন্ধ করার ঝুঁকিটি চালান।
অ্যাডাম লাসেক

@ আইভোও আমি যে কোডের উপর নির্ভর করি সে সম্পর্কে আমি খুব সতর্ক setTimeout। কোডটি আপনার প্রত্যাশার চেয়ে দ্রুত কার্যকর করা হলে আপনি অনিচ্ছাকৃত আচরণের ঝুঁকি নিতে পারেন।
অ্যাডাম লাসেক

@ অ্যাডাম কোনভাবেই যদি কলব্যাকটি setTimeoutকেবল অর্ধেক সময় নেয় তবে আমি কী দিয়ে অনিচ্ছাকৃত আচরণের ঝুঁকি নেব , ঠিক আছে কোডটি আবার দ্রুত কার্যকর করা হয় ... তবে কী কথা? "লুপ" এর "কোড "টি এখনও ঠিক আছে, আপনি যদি ইতিমধ্যে সমস্যার জন্য ডাকছেন সম্পূর্ণ কলব্যাকের আগে আপনি যদি এর বাইরে কিছু স্টাফ করেন তবে এটি আবার একক থ্রেডেড, আমার সাথে একটি কঠিন সময় আসতে হবে পরিস্থিতি যেখানে setTimeoutকোনও ভুল নকশা ছাড়াই কিছু ভঙ্গ করবে।
আইভো ওয়েটজেল

এছাড়াও, তিনি অন্য প্রশ্নে নোড.জেএস এর মতো মডিউল চেয়েছিলেন, আমি সেখানে বলেছিলাম যে এই জাতীয় "এসিএনসি-সিঙ্ক" লুপগুলির জেনেরিক সমাধান করা সাধারণভাবে খারাপ ধারণা। আমি বরং এমন কিছু সাথে যাব যা আমি অর্জন করার চেষ্টা করছি তার সঠিক প্রয়োজনীয়তার সাথে মেলে।
আইভো ওয়েটজেল

3

এছাড়াও এই দুর্দান্ত লাইব্রেরি caolan / async দেখুন । আপনার forলুপটি মানচিত্রগুলি বা সিরিজগুলি ব্যবহার করে সহজেই সম্পাদন করা যায়

আপনার উদাহরণটিতে আরও বিশদ থাকলে আমি কিছু নমুনা কোড পোস্ট করতে পারি।


2

আমরা jquery.Deferred এর সহায়তাও ব্যবহার করতে পারি। এক্ষেত্রে asyncLoop ফাংশনটি দেখতে এরকম হবে:

asyncLoop = function(array, callback) {
  var nextElement, thisIteration;
  if (array.length > 0) nextElement = array.pop();
  thisIteration = callback(nextElement);
  $.when(thisIteration).done(function(response) {
    // here we can check value of response in order to break or whatever
    if (array.length > 0) asyncLoop(array, collection, callback);
  });
};

কলব্যাক ফাংশনটি এর মতো দেখাবে:

addEntry = function(newEntry) {
  var deferred, duplicateEntry;
  // on the next line we can perform some check, which may cause async response.
  duplicateEntry = someCheckHere();
  if (duplicateEntry === true) {
    deferred = $.Deferred();
    // here we launch some other function (e.g. $.ajax or popup window) 
    // which based on result must call deferred.resolve([opt args - response])
    // when deferred.resolve is called "asyncLoop" will start new iteration
    // example function:
    exampleFunction(duplicateEntry, deferred);
    return deferred;
  } else {
    return someActionIfNotDuplicate();
  }
};

পিছনে সমাধানের ফাংশন উদাহরণ:

function exampleFunction(entry, deffered){
  openModal({
    title: "what should we do with duplicate"
    options: [
       {name:"Replace", action: function(){replace(entry);deffered.resolve(replace:true)}},
       {name: "Keep Existing", action: function(){deffered.resolve(replace:false)}}
    ]
  })
}

2

আমি "সেটটাইমআউট (ফানক, 0)" ব্যবহার করছি; প্রায় বছরের জন্য কৌশল কীভাবে এটি কিছুটা গতি বাড়ানো যায় তা বোঝাতে আমি সাম্প্রতিক কিছু গবেষণা এখানে লিখেছি। যদি আপনি কেবল উত্তরটি চান, তবে পদক্ষেপ 4 এ যান Step

// In Depth Analysis of the setTimeout(Func,0) trick.

//////// setTimeout(Func,0) Step 1 ////////////
// setTimeout and setInterval impose a minimum 
// time limit of about 2 to 10 milliseconds.

  console.log("start");
  var workCounter=0;
  var WorkHard = function()
  {
    if(workCounter>=2000) {console.log("done"); return;}
    workCounter++;
    setTimeout(WorkHard,0);
  };

// this take about 9 seconds
// that works out to be about 4.5ms per iteration
// Now there is a subtle rule here that you can tweak
// This minimum is counted from the time the setTimeout was executed.
// THEREFORE:

  console.log("start");
  var workCounter=0;
  var WorkHard = function()
  {
    if(workCounter>=2000) {console.log("done"); return;}
    setTimeout(WorkHard,0);
    workCounter++;
  };

// This code is slightly faster because we register the setTimeout
// a line of code earlier. Actually, the speed difference is immesurable 
// in this case, but the concept is true. Step 2 shows a measurable example.
///////////////////////////////////////////////


//////// setTimeout(Func,0) Step 2 ////////////
// Here is a measurable example of the concept covered in Step 1.

  var StartWork = function()
  {
    console.log("start");
    var startTime = new Date();
    var workCounter=0;
    var sum=0;
    var WorkHard = function()
    {
      if(workCounter>=2000) 
      {
        var ms = (new Date()).getTime() - startTime.getTime();
        console.log("done: sum=" + sum + " time=" + ms + "ms"); 
        return;
      }
      for(var i=0; i<1500000; i++) {sum++;}
      workCounter++;
      setTimeout(WorkHard,0);
    };
    WorkHard();
  };

// This adds some difficulty to the work instead of just incrementing a number
// This prints "done: sum=3000000000 time=18809ms".
// So it took 18.8 seconds.

  var StartWork = function()
  {
    console.log("start");
    var startTime = new Date();
    var workCounter=0;
    var sum=0;
    var WorkHard = function()
    {
      if(workCounter>=2000) 
      {
        var ms = (new Date()).getTime() - startTime.getTime();
        console.log("done: sum=" + sum + " time=" + ms + "ms"); 
        return;
      }
      setTimeout(WorkHard,0);
      for(var i=0; i<1500000; i++) {sum++;}
      workCounter++;
    };
    WorkHard();
  };

// Now, as we planned, we move the setTimeout to before the difficult part
// This prints: "done: sum=3000000000 time=12680ms"
// So it took 12.6 seconds. With a little math, (18.8-12.6)/2000 = 3.1ms
// We have effectively shaved off 3.1ms of the original 4.5ms of dead time.
// Assuming some of that time may be attributed to function calls and variable 
// instantiations, we have eliminated the wait time imposed by setTimeout.

// LESSON LEARNED: If you want to use the setTimeout(Func,0) trick with high 
// performance in mind, make sure your function takes more than 4.5ms, and set 
// the next timeout at the start of your function, instead of the end.
///////////////////////////////////////////////


//////// setTimeout(Func,0) Step 3 ////////////
// The results of Step 2 are very educational, but it doesn't really tell us how to apply the
// concept to the real world.  Step 2 says "make sure your function takes more than 4.5ms".
// No one makes functions that take 4.5ms. Functions either take a few microseconds, 
// or several seconds, or several minutes. This magic 4.5ms is unattainable.

// To solve the problem, we introduce the concept of "Burn Time".
// Lets assume that you can break up your difficult function into pieces that take 
// a few milliseconds or less to complete. Then the concept of Burn Time says, 
// "crunch several of the individual pieces until we reach 4.5ms, then exit"

// Step 1 shows a function that is asyncronous, but takes 9 seconds to run. In reality
// we could have easilly incremented workCounter 2000 times in under a millisecond.
// So, duh, that should not be made asyncronous, its horrible. But what if you don't know
// how many times you need to increment the number, maybe you need to run the loop 20 times,
// maybe you need to run the loop 2 billion times.

  console.log("start");
  var startTime = new Date();
  var workCounter=0;
  for(var i=0; i<2000000000; i++) // 2 billion
  {
    workCounter++;
  }
  var ms = (new Date()).getTime() - startTime.getTime();
  console.log("done: workCounter=" + workCounter + " time=" + ms + "ms"); 

// prints: "done: workCounter=2000000000 time=7214ms"
// So it took 7.2 seconds. Can we break this up into smaller pieces? Yes.
// I know, this is a retarded example, bear with me.

  console.log("start");
  var startTime = new Date();
  var workCounter=0;
  var each = function()
  {
    workCounter++;
  };
  for(var i=0; i<20000000; i++) // 20 million
  {
    each();
  }
  var ms = (new Date()).getTime() - startTime.getTime();
  console.log("done: workCounter=" + workCounter + " time=" + ms + "ms"); 

// The easiest way is to break it up into 2 billion smaller pieces, each of which take 
// only several picoseconds to run. Ok, actually, I am reducing the number from 2 billion
// to 20 million (100x less).  Just adding a function call increases the complexity of the loop
// 100 fold. Good lesson for some other topic.
// prints: "done: workCounter=20000000 time=7648ms"
// So it took 7.6 seconds, thats a good starting point.
// Now, lets sprinkle in the async part with the burn concept

  console.log("start");
  var startTime = new Date();
  var workCounter=0;
  var index=0;
  var end = 20000000;
  var each = function()
  {
    workCounter++;
  };
  var Work = function()
  {
    var burnTimeout = new Date();
    burnTimeout.setTime(burnTimeout.getTime() + 4.5); // burnTimeout set to 4.5ms in the future
    while((new Date()) < burnTimeout)
    {
      if(index>=end) 
      {
        var ms = (new Date()).getTime() - startTime.getTime();
        console.log("done: workCounter=" + workCounter + " time=" + ms + "ms"); 
        return;
      }
      each();
      index++;
    }
    setTimeout(Work,0);
  };

// prints "done: workCounter=20000000 time=107119ms"
// Sweet Jesus, I increased my 7.6 second function to 107.1 seconds.
// But it does prevent the browser from locking up, So i guess thats a plus.
// Again, the actual objective here is just to increment workCounter, so the overhead of all
// the async garbage is huge in comparison. 
// Anyway, Lets start by taking advice from Step 2 and move the setTimeout above the hard part. 

  console.log("start");
  var startTime = new Date();
  var workCounter=0;
  var index=0;
  var end = 20000000;
  var each = function()
  {
    workCounter++;
  };
  var Work = function()
  {
    if(index>=end) {return;}
    setTimeout(Work,0);
    var burnTimeout = new Date();
    burnTimeout.setTime(burnTimeout.getTime() + 4.5); // burnTimeout set to 4.5ms in the future
    while((new Date()) < burnTimeout)
    {
      if(index>=end) 
      {
        var ms = (new Date()).getTime() - startTime.getTime();
        console.log("done: workCounter=" + workCounter + " time=" + ms + "ms"); 
        return;
      }
      each();
      index++;
    }
  };

// This means we also have to check index right away because the last iteration will have nothing to do
// prints "done: workCounter=20000000 time=52892ms"  
// So, it took 52.8 seconds. Improvement, but way slower than the native 7.6 seconds.
// The Burn Time is the number you tweak to get a nice balance between native loop speed
// and browser responsiveness. Lets change it from 4.5ms to 50ms, because we don't really need faster
// than 50ms gui response.

  console.log("start");
  var startTime = new Date();
  var workCounter=0;
  var index=0;
  var end = 20000000;
  var each = function()
  {
    workCounter++;
  };
  var Work = function()
  {
    if(index>=end) {return;}
    setTimeout(Work,0);
    var burnTimeout = new Date();
    burnTimeout.setTime(burnTimeout.getTime() + 50); // burnTimeout set to 50ms in the future
    while((new Date()) < burnTimeout)
    {
      if(index>=end) 
      {
        var ms = (new Date()).getTime() - startTime.getTime();
        console.log("done: workCounter=" + workCounter + " time=" + ms + "ms"); 
        return;
      }
      each();
      index++;
    }
  };

// prints "done: workCounter=20000000 time=52272ms"
// So it took 52.2 seconds. No real improvement here which proves that the imposed limits of setTimeout
// have been eliminated as long as the burn time is anything over 4.5ms
///////////////////////////////////////////////


//////// setTimeout(Func,0) Step 4 ////////////
// The performance numbers from Step 3 seem pretty grim, but GUI responsiveness is often worth it.
// Here is a short library that embodies these concepts and gives a descent interface.

  var WilkesAsyncBurn = function()
  {
    var Now = function() {return (new Date());};
    var CreateFutureDate = function(milliseconds)
    {
      var t = Now();
      t.setTime(t.getTime() + milliseconds);
      return t;
    };
    var For = function(start, end, eachCallback, finalCallback, msBurnTime)
    {
      var i = start;
      var Each = function()
      {
        if(i==-1) {return;} //always does one last each with nothing to do
        setTimeout(Each,0);
        var burnTimeout = CreateFutureDate(msBurnTime);
        while(Now() < burnTimeout)
        {
          if(i>=end) {i=-1; finalCallback(); return;}
          eachCallback(i);
          i++;
        }
      };
      Each();
    };
    var ForEach = function(array, eachCallback, finalCallback, msBurnTime)
    {
      var i = 0;
      var len = array.length;
      var Each = function()
      {
        if(i==-1) {return;}
        setTimeout(Each,0);
        var burnTimeout = CreateFutureDate(msBurnTime);
        while(Now() < burnTimeout)
        {
          if(i>=len) {i=-1; finalCallback(array); return;}
          eachCallback(i, array[i]);
          i++;
        }
      };
      Each();
    };

    var pub = {};
    pub.For = For;          //eachCallback(index); finalCallback();
    pub.ForEach = ForEach;  //eachCallback(index,value); finalCallback(array);
    WilkesAsyncBurn = pub;
  };

///////////////////////////////////////////////


//////// setTimeout(Func,0) Step 5 ////////////
// Here is an examples of how to use the library from Step 4.

  WilkesAsyncBurn(); // Init the library
  console.log("start");
  var startTime = new Date();
  var workCounter=0;
  var FuncEach = function()
  {
    if(workCounter%1000==0)
    {
      var s = "<div></div>";
      var div = jQuery("*[class~=r1]");
      div.append(s);
    }
    workCounter++;
  };
  var FuncFinal = function()
  {
    var ms = (new Date()).getTime() - startTime.getTime();
    console.log("done: workCounter=" + workCounter + " time=" + ms + "ms"); 
  };
  WilkesAsyncBurn.For(0,2000000,FuncEach,FuncFinal,50);

// prints: "done: workCounter=20000000 time=149303ms"
// Also appends a few thousand divs to the html page, about 20 at a time.
// The browser is responsive the entire time, mission accomplished

// LESSON LEARNED: If your code pieces are super tiny, like incrementing a number, or walking through 
// an array summing the numbers, then just putting it in an "each" function is going to kill you. 
// You can still use the concept here, but your "each" function should also have a for loop in it 
// where you burn a few hundred items manually.  
///////////////////////////////////////////////

2

একটি অ্যাসিক্রোনাস ওয়ার্কার ফাংশন দেওয়া হয়েছে যা লুপটি চালিয়ে যাওয়া উচিত কিনা তা এই যুক্তি someFunctionসহ একটি ফলাফল ফাংশন আবার কল করবে result:

// having:
// function someFunction(param1, praram2, resultfunc))
// function done() { alert("For cycle ended"); }

(function(f){ f(f) })(function(f){
  someFunction("param1", "praram2", function(result){
    if (result)
      f(f); // loop continues
    else
      done(); // loop ends
  });
})

লুপটি শেষ করতে হবে কিনা তা পরীক্ষা করার জন্য, কর্মী ফাংশন someFunctionফলাফল ফাংশনটিকে অন্যান্য অ্যাসিনক্রোনাস অপারেশনে ফরোয়ার্ড করতে পারে। এছাড়াও, পুরো doneভাবটি কলব্যাক হিসাবে একটি ফাংশন গ্রহণ করে একটি অ্যাসিঙ্ক্রোনাস ফাংশনে আবদ্ধ করা যায় ।


1

আপনি যদি উইলসনপেজের উত্তরটি পছন্দ করেন তবে async.js এর বাক্য গঠনটি ব্যবহার করতে বেশি অভ্যস্ত হন, এখানে একটি ভিন্নতা রয়েছে:

function asyncEach(iterableList, callback, done) {
  var i = -1,
      length = iterableList.length;

  function loop() {
      i++;
      if (i === length) {
        done(); 
        return;
      }
      callback(iterableList[i], loop);
  } 
  loop();
}


asyncEach(['A', 'B', 'C'], function(item, callback) {
    setTimeout(function(){
    document.write('Iteration ' + item + ' <br>');
    callback();
  }, 1000);
}, function() {
  document.write('All done!');
});

ডেমোটি এখানে পাওয়া যাবে - http://jsf رکن.net / NXTv7/8/


1

এখানে অন্য একটি উদাহরণ যা আমি মনে করি অন্যের তুলনায় বেশি পঠনযোগ্য, আপনি যেখানে আপনার অ্যাসিঙ্ক ফাংশনটি কোনও doneফাংশন, বর্তমান লুপ সূচী এবং তার পূর্ববর্তী অ্যাসিঙ্ক কলটির ফলাফল (যদি থাকে) এর মধ্যে আবদ্ধ করেন:

function (done, i, prevResult) {
   // perform async stuff
   // call "done(result)" in async callback 
   // or after promise resolves
}

একবার done()আহ্বান করা হয়ে গেলে এটি পরবর্তী সম্পন্ন ফাংশন, বর্তমান সূচি এবং পূর্ববর্তী ফলাফলের মধ্যে দিয়ে পরবর্তী অ্যাসিঙ্ক কলটি ট্রিগার করে। পুরো লুপটি শেষ হয়ে গেলে প্রদত্ত লুপটি callbackচালু করা হবে।

আপনি চালাতে পারেন এমন একটি স্নিপেট এখানে:

asyncLoop({
  limit: 25,
  asyncLoopFunction: function(done, i, prevResult) {
    setTimeout(function() {
      console.log("Starting Iteration: ", i);
      console.log("Previous Result: ", prevResult);
      var result = i * 100;
      done(result);
    }, 1000);
  },
  initialArgs: 'Hello',
  callback: function(result) {
    console.log('All Done. Final result: ', result);
  }
});

function asyncLoop(obj) {
  var limit = obj.limit,
    asyncLoopFunction = obj.asyncLoopFunction,
    initialArgs = obj.initialArgs || {},
    callback = obj.callback,
    i = 0;

  function done(result) {
    i++;
    if (i < limit) {
      triggerAsync(result);
    } else {
      callback(result);
    }
  }

  function triggerAsync(prevResult) {
    asyncLoopFunction(done, i, prevResult);
  }

  triggerAsync(initialArgs); // init
}


1

আপনি async awaitES7 এ চালু ব্যবহার করতে পারেন :

for ( /* ... */ ) {
    let result = await someFunction(param1, param2);
}
alert("For cycle ended");

এটি কেবল তখন someFunctionপ্রতিশ্রুতি দিলে কাজ করে !

যদি someFunctionকোনও প্রতিশ্রুতি না ফেরায়, তবে আপনি এটিকে নিজের দ্বারা প্রতিশ্রুতি ফিরিয়ে দিতে পারেন:

function asyncSomeFunction(param1,praram2) {
  return new Promise((resolve, reject) => {
    someFunction(praram1,praram2,(result)=>{
      resolve(result);
    })
  })
}

তারপর এই লাইন প্রতিস্থাপন await someFunction(param1, param2);দ্বারাawait asynSomeFunction(param1, param2);

async awaitকোড লেখার আগে প্রতিশ্রুতি বুঝতে দয়া করে !


এই দেওয়া উচিত Unexpected await inside loop
রেয়ারা

@ রিয়ার যে javascriptইস্যু নয় । সেই সতর্কতাটি আপনার eslintকনফিগারেশন থেকে আসে । আমি সর্বদা এই নিয়মটি অক্ষম করে থাকি eslintকারণ বেশিরভাগ জায়গায় আমার সত্যিকারের লুপের অভ্যন্তরে অপেক্ষা করা দরকার
প্রবীণ

0

http://cuzztuts.blogspot.ro/2011/12/js-async-for-very-cool.html

সম্পাদনা:

গিথুব থেকে লিঙ্ক: https://github.com/cuzzea/lib_repo/blob/master/cuzzea/js/funitions/core/async_for.js

function async_for_each(object,settings){
var l=object.length;
    settings.limit = settings.limit || Math.round(l/100);
    settings.start = settings.start || 0;
    settings.timeout = settings.timeout || 1;
    for(var i=settings.start;i<l;i++){
        if(i-settings.start>=settings.limit){
            setTimeout(function(){
                settings.start = i;
                async_for_each(object,settings)
            },settings.timeout);
            settings.limit_callback ? settings.limit_callback(i,l) : null;
            return false;
        }else{
            settings.cbk ? settings.cbk(i,object[i]) : null;
        }
    }
    settings.end_cbk?settings.end_cbk():null;
    return true;
}

এই ফাংশনটি আপনাকে সেটিংস.লিট ব্যবহার করে লুপের জন্য একটি শতাংশ বিরতি তৈরি করতে দেয়। সীমাটির সম্পত্তিটি কেবল একটি পূর্ণসংখ্যা, তবে অ্যারে. দৈর্ঘ্য * 0.1 হিসাবে সেট করা থাকলে এটি সেটিংসটি তৈরি করবে lim

/*
 * params:
 *  object:         the array to parse
 *  settings_object:
 *      cbk:            function to call whenwhen object is found in array
 *                          params: i,object[i]
 *      limit_calback:  function to call when limit is reached
 *                          params: i, object_length
 *      end_cbk:        function to call when loop is finished
 *                          params: none
 *      limit:          number of iteration before breacking the for loop
 *                          default: object.length/100
 *      timeout:        time until start of the for loop(ms)
 *                          default: 1
 *      start:          the index from where to start the for loop
 *                          default: 0
 */

উদাহরণ:

var a = [];
a.length = 1000;
async_for_each(a,{
    limit_callback:function(i,l){console.log("loading %s/%s - %s%",i,l,Math.round(i*100/l))}
});

0

একটি প্রতিশ্রুতি গ্রন্থাগার ভিত্তিক সমাধান:

/*
    Since this is an open question for JS I have used Kris Kowal's Q promises for the same
*/

var Q = require('q');
/*
    Your LOOP body
    @success is a parameter(s) you might pass
*/
var loopBody = function(success) {
    var d = Q.defer(); /* OR use your favorite promise library like $q in angular */
    /*
        'setTimeout' will ideally be your node-like callback with this signature ... (err, data) {}
        as shown, on success you should resolve 
        on failure you should reject (as always ...) 
    */
    setTimeout(function(err, data) {
        if (!err) {
            d.resolve('success');
        } else {
            d.reject('failure');
        }
    }, 100); //100 ms used for illustration only 
    return d.promise;
};

/*
    function to call your loop body 
*/
function loop(itr, fn) {
    var def = Q.defer();
    if (itr <= 0) {
        def.reject({ status: "un-successful " });
    } else {
        var next = loop.bind(undefined, itr - 1, fn); // 'next' is all there is to this 
        var callback = fn.bind(undefined /*, a, b, c.... */ ); // in case you want to pass some parameters into your loop body
        def.promise = callback().then(def.resolve, next);
    }
    return def.promise;
}
/*
    USAGE: loop(iterations, function(){})
    the second argument has to be thenable (in other words return a promise)
    NOTE: this loop will stop when loop body resolves to a success
    Example: Try to upload file 3 times. HURRAY (if successful) or log failed 
*/

loop(4, loopBody).then(function() {
    //success handler
    console.log('HURRAY')
}, function() {
    //failed 
    console.log('failed');
});

0

আমাকে কিছু অ্যাসিনক্রোনাস ফাংশনের Xসময় কল করতে হবে , প্রতিটি পুনরাবৃত্তি অবশ্যই পূর্ববর্তীটি সম্পন্ন হওয়ার পরে ঘটেছে, তাই আমি একটি লিট্র লাইব্রেরি লিখেছিলাম যা এটি ব্যবহার করা যেতে পারে:

// https://codepen.io/anon/pen/MOvxaX?editors=0012
var loop = AsyncLoop(function(iteration, value){
  console.log("Loop called with iteration and value set to: ", iteration, value);

  var random = Math.random()*500;

  if(random < 200)
    return false;

  return new Promise(function(resolve){
    setTimeout(resolve.bind(null, random), random);
  });
})
.finished(function(){
  console.log("Loop has ended");
});

প্রতিবার ব্যবহারকারী সংজ্ঞায়িত লুপ ফাংশনটি বলা হয়, এর দুটি আর্গুমেন্ট, পুনরাবৃত্তি সূচক এবং পূর্ববর্তী কল রিটার্ন মান থাকে।

এটি আউটপুট উদাহরণ:

"Loop called with iteration and value set to: " 0 null
"Loop called with iteration and value set to: " 1 496.4137048207333
"Loop called with iteration and value set to: " 2 259.6020382449663
"Loop called with iteration and value set to: " 3 485.5400568702862
"Loop has ended"
আমাদের সাইট ব্যবহার করে, আপনি স্বীকার করেছেন যে আপনি আমাদের কুকি নীতি এবং গোপনীয়তা নীতিটি পড়েছেন এবং বুঝতে পেরেছেন ।
Licensed under cc by-sa 3.0 with attribution required.