本文介绍了如何在没有async.waterfall的情况下在javascript(或)jquery中为数据数组编写核心逻辑瀑布回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列ajax调用,它们逐个执行。在任何ajax调用失败之间它应该失败像瀑布这样的剩余调用。

I have array of ajax calls which executes one by one. in between any ajax call fails it should fails remaining calls like waterfall.

var waterfallData = [{
    "name":"nodejs"
},{
    "name":"javascript"
},{
    "name":"angularjs"
},{
    "name":"mongodb"
}];

function wf(data,cb){
    if(data.name == "angularjs"){
        cb(null,"error");
    }else{
        cb(data,null);
    }
}

var finalData = {
    "dataCheck":""
}
waterfallData.forEach(function(checkData) {
        wf(checkData,function(result){
            console.log(result);
            return true;
        },function(err){
            console.log("error",err);
            return false;
        })
    });

此处它正在作为系列调用执行。但我不想使用异步瀑布。

Here it is executing as series calls. but i don't want to use async waterfall.

我想在任何情况下失败时停止循环。谁可以帮我这个事。
提前感谢

i want to stop loop if any case fails. can anyone help me on this.thanks in advance

推荐答案

你可以宣传你的 wf 功能和迭代 waterfallData 使用 for-loop

You can promisify your wf function and iterate waterfallData using for-loop

function promiseWF( data )
{
   return new Promise( ( resolve, reject ) => {
      if( data.name == "angularjs"){
         reject(null,"error");
      }
      else{
         resolve(data,null);
      }
   });
}

现在你可以使用简单的 for-loop successFlag

Now you can use simple for-loop with successFlag

  async function waterFallInSequence() 
  {
    var successFlag = true;
    for (var counter = 0; successFlag && counter < waterfallData.length; counter++) 
    {
      await promiseWF( waterfallData[ counter ] )
         .then( ( result ) => { 
             console.log( result ); 
         }) 
         .catch( ( error ) => { 
             console.log( error ); 
             successFlag =  false; //make this flag false so that for-loop fails
         })
    }
  }

这篇关于如何在没有async.waterfall的情况下在javascript(或)jquery中为数据数组编写核心逻辑瀑布回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 22:59