How to write core logic waterfall callback for arr

2019-05-19 23:33发布

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

2条回答
劫难
2楼-- · 2019-05-19 23:47

If they're ajax calls, then you should use code with Fetch and Promises. Put the code into an async function, and then do:

for (obj of waterfallData) {
  const response = await obj.name; // or whevever you get the URL from
  if (!response.ok) {
    // the response failed for some reason,
    // break out of this iteration and do not do any more iterations:
    break;
  }
  const responseText = await response.text();
  // do other stuff with the responseText
}
查看更多
Viruses.
3楼-- · 2019-05-20 00:06

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);
      }
   });
}

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
         })
    }
  }
查看更多
登录 后发表回答