Sample code for JavaScript to implement serial request

  • 2021-08-16 23:08:50
  • OfStack

Using async and await


var fn = async function(promiseArr) {
 for(let i = 0,len = arr.length; i<len; i++) {
  currentPromise = (promiseArr[i] instanceOf Promise) ? promiseArr[i] : Promise.resolve(promiseArr[i]);
  var result = await currentPromise;
  console.log(result)
 }
 }
 fn(arr)

Promise Implementation

According to the promises specification, once an promise is created, it is executed. If an promise object is returned in the then method, the next then must be executed after the last then.

The key point is to create it when then


var createPromise = function(time) {
 return (resolve, reject)=> {
  return new Promise((resolve, reject)=>{
   setTimeout(()=>{
    console.log('timein'+time)
    resolve();
   }, time*1000)
  })
 }
}

function serpromise(arr) {
 arr.reduce((pre, next, index, carr)=>{
  return pre.then(next)
 }, Promise.resolve())
}

var arr=[createPromise(2),createPromise(1),createPromise(3),createPromise(4),createPromise(5)];
//  Equivalent to 
// Promise.resolve().then(createPromise(2)).then(createPromise(1))......
serpromise(arr)

Array. prototype. reduce + async/await version


const reduceAsync = ( arr ) => {
 arr.reduce( async ( prev, curr ) => {
  const { rep } = await prev;
  const obj = await promise( curr, rep );
  console.log( obj );
  return obj;
 }, Promise.resolve( {} ) );
};

Array. prototype. reduce + Promise version


const reducePromise = ( arr ) => {
 arr.reduce( ( prev, curr ) => {
  return prev.then( data => {
   return new Promise( ( resolve, reject ) => {
    promise( curr, data.rep ).then( res => {
     console.log( res );
     resolve( res );
    } );
   } );
  } );
 }, Promise.resolve( {} ) );
};

# Implementation results
{ req: 'PM:04:49:08', rep: 'PM:04:49:11', item: 1 }
{ req: 'PM:04:49:11', rep: 'PM:04:49:14', item: 2 }
{ req: 'PM:04:49:14', rep: 'PM:04:49:17', item: 3 }
{ req: 'PM:04:49:17', rep: 'PM:04:49:20', item: 4 }

Array. prototype. map + Promise version


const mapPromise = ( arr ) => {
 let temporary = Promise.resolve( {} );
 arr.map( ( item, index ) => {
  temporary = temporary.then( ( data ) => {
   if (i !== 0) {
    //  No. 1 1 Initial promise
    console.log( data );
   }
   return promise( item, data.rep );
  } );
 } );
 //  Finally 1 A promise
 temporary.then( data => console.log( data ) );
};

When using map, you need to filter the return value of the initial promise, and after the iteration, you need to manually execute the last promise, otherwise it will become the following result

# Implementation results
{}
{ req: 'PM:04:49:08', rep: 'PM:04:49:11', item: 1 }
{ req: 'PM:04:49:11', rep: 'PM:04:49:14', item: 2 }
{ req: 'PM:04:49:14', rep: 'PM:04:49:17', item: 3 }

The above results are obviously not what we need, but we need to manually filter the first promise and execute the last promise, which will add unnecessary code amount and error rate. After modifying mapPromise as follows, its principle is similar to Array. prototype. reduce+Promise version


const mapPromise = ( arr ) => {
 let temporary = Promise.resolve( {} );
 arr.map( ( item, index ) => {
  temporary = temporary.then( ( data ) => {
   // if (i !== 0) {
   //  //  No. 1 1 A promise
   //  console.log( data );
   // }
   return new Promise( ( resolve, reject ) => {
    promise( item, data.rep ).then( data => {
     console.log( data );
     resolve( data );
    } );
   } );
  } );
 } );
 //  Finally 1 A promise
 // temporary.then( d => console.log( d ) );
};

Others

Array. prototype. forEach, Array. ES90filter, Array. prototype. some, Array. prototype. every and other methods are similar to Array. prototype. map, so we will not go into details

The above is the JavaScript implementation of serial request sample code details, more about JavaScript implementation of serial request information please pay attention to other related articles on this site!


Related articles: