promise函数队列执行问题

//Promise封装的函数

function app(num,data){

 

}

如果想调用成功后再次去执行自身


var data=[...]

//执行次数为data.length=3

app(0)

.then(function(res){

    console.log(res)

    return app(1)

})

.then(function(res){

     console.log(res)

    return app(2)

});

执行次数如果不确定该怎么去实现,上面执行了3次,返回的data数据长度不确定。


慕勒3428872
浏览 553回答 3
3回答

开心每一天1111

function app (num, data) {&nbsp; return new Promise(function (resolve, reject) {&nbsp; &nbsp; resolve(num)&nbsp; })}let data = [1, 2, 3]let res = Promise.resolve()for (let index = 0; index < data.length; index++) {&nbsp; res = res.then(v => {&nbsp; &nbsp; console.log(v)&nbsp; &nbsp; return app(index)&nbsp; })}

郎朗坤

如果你每次执行app()互相没有联系 可以放在一个数组里 用Promise.all来执行let p =[]for(let i=0;i<data.length;i++){&nbsp; p.push(app(i,data))}Promise.all(p).then(res=>{&nbsp; console.log(res)})

qq_花开花谢_0

function app(num, data) {&nbsp; &nbsp; return new Promise(function (resolve, reject) {&nbsp; &nbsp; &nbsp; &nbsp; resolve(num)&nbsp; &nbsp; })}function test(arr, cb) {&nbsp; &nbsp; return arr.reduce((p, v) => p.then(() => cb(v)), Promise.resolve())}test([4, 1, 9], function (num) {&nbsp; &nbsp; return app(num).then(res => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(res)&nbsp; &nbsp; });})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript