gpt4 book ai didi

javascript - 我怎样才能摆脱这个 Promise for 循环?

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:18 25 4
gpt4 key购买 nike

编辑:我知道如何使用 async/await 让它工作,但不幸的是,我无法使用它,因为它没有得到广泛支持(特别是 iOS 10、Internet Explorer 等)。所以我需要一种只有 promise 的方法。

我对 Promise 非常陌生,所以我陷入了困境。我有一个 for 循环,每当 i 等于 2 时我就想打破它(仅作为示例)。我尝试过输入 reject但它仍然继续直到 i<10 。我希望它在满足我的条件时停止。

for (let i = 0, p = Promise.resolve(); i < 10; i++) {
p = p.then(_ => new Promise((resolve, reject) => {
setTimeout(function() {
console.log(i);
if (i == 2) {
reject("BREAK HERE");
} else {
resolve();
}
}, Math.random() * 1000)
})).catch(err => {
console.log(err);
});
}

当前输出:

0
1
2
BREAK HERE
3
4
5
6
7
8
9

我希望它是:

0
1
2
BREAK HERE

最佳答案

只要不解析,序列就会停止

for (let i = 0, p = Promise.resolve(); i < 10; i++) {
p = p.then(_ => new Promise((resolve, reject) => {
setTimeout(function() {
console.log("i",i);
if (i == 2) {
console.log("break here")

} else {
resolve();
}
}, Math.random() * 1000)
})).catch(err => {
console.log("err",err);
});
}

但是由于此代码本身旨在对异步调用进行排序,因此应该考虑这样做:

// repeated call
next(
0/*state*/,
i=>i<2/*match*/,
i=>i+1/*increment*/,
asyncCallPromisefied/*promise|promise[]*/,
[0]/*args*/
)
.catch(console.log)


// traverse array
next(
0/*state*/,
i => i < 6/*match*/,
i => i + 1/*increment*/,
asyncChain()/*promise|promise[]*/,
[0]/*args*/,
0/*[promise[] index]*/
)
.catch(console.log)


// helper
function next(state, match, increment, action, args, pointer = 0/**inactive**/){
if(match(state))
if(Array.isArray(action)){

return pointer < action.length
? action[pointer](...args)
.then(i => next(
increment(state),
match,
increment,
action,
[i],
pointer + 1
))
: undefined;
} else {
return action(...args)
.then(i => next(
increment(state),
match,
increment,
action,
[i]
))
}
}



// wrapper
function asyncCall(i, callback){
return setTimeout(() => {
console.log(i == 2 ? 'break here': i);
callback(null, ++i);
}, Math.random() * 1000)
}

function asyncCallPromisefied(i){
return new Promise(function(resolve, reject){
asyncCall(i, function(err, args){
if(err){
reject(err)
} else {
resolve(args)
}
})
})
}

function asyncChain(){return [
function(i){console.log("chain",i);return Promise.resolve(i)},
function(i){console.log("chain",i);return Promise.resolve(i)},
function(i){console.log("chain",i);return Promise.resolve(i)},
asyncCallPromisefied,
function(i){console.log("chain",i);return Promise.resolve(i)},
]}

关于javascript - 我怎样才能摆脱这个 Promise for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57754795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com