(编辑:jimmy 日期: 2024/11/10 浏览:2)
使用async和await
var fn = async function(promiseArr) { for(let i = 0,len = arr.length; i<len; i++) { currentPromise = (promiseArr[i] instanceOf Promise) "htmlcode">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)]; // 相当于 // Promise.resolve().then(createPromise(2)).then(createPromise(1))...... serpromise(arr)Array.prototype.reduce + async/await 版本
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 版本
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( {} ) ); };# 执行结果
{ 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 版本
const mapPromise = ( arr ) => { let temporary = Promise.resolve( {} ); arr.map( ( item, index ) => { temporary = temporary.then( ( data ) => { if (i !== 0) { // 第一个初始promise console.log( data ); } return promise( item, data.rep ); } ); } ); // 最后一个promise temporary.then( data => console.log( data ) ); };用 map 遍历时,需要过滤初始promise的返回值,并且在遍历结束后,需手动执行最后以后一个promise,否则就会变成如下结果
# 执行结果
{}
{ 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 }以上结果明显不是我们所需要的,但是需要手动过滤第一个promise和执行最后一个promise,会增项不必要的代码量和出错率 后将 mapPromise 修改如下,其原理和Array.prototype.reduce+Promise版本类似
const mapPromise = ( arr ) => { let temporary = Promise.resolve( {} ); arr.map( ( item, index ) => { temporary = temporary.then( ( data ) => { // if (i !== 0) { // // 第一个promise // console.log( data ); // } return new Promise( ( resolve, reject ) => { promise( item, data.rep ).then( data => { console.log( data ); resolve( data ); } ); } ); } ); } ); // 最后一个promise // temporary.then( d => console.log( d ) ); };其他
Array.prototype.forEach、Array.prototype.filter、Array.prototype.some、Array.prototype.every等方法和Array.prototype.map类似,就不过多赘述
以上就是JavaScript实现串行请求的示例代码的详细内容,更多关于JavaScript实现串行请求的资料请关注其它相关文章!