在for循环中打破Promise链 [英] Break a Promise chain inside for-loop

查看:143
本文介绍了在for循环中打破Promise链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究受此答案启发的承诺链:
https://stackoverflow.com/a / 44955506/7485805



我想打破此for循环,以正确处理链条被拒的情况。我只是想知道我不能在链的 .catch 方法内使用 break



如果有帮助,这是我的代码:

  function pro(arr){
让链= Promise.resolve();
const self = {req:{},res:{}};
const length = arr.length;

返回新的Promise((解决,拒绝)=> {
for(让i = 0; i 链=链
.then(()=> arr [i] .call(self))
.then(()=> {
if(i ===(length-1))
resolve();
})
.catch(e => {
reject(e);
})
}
})
.then(()=> {
return self
})
.catch(e => {
抛出新错误(e);
})

}

const x = function(){
const self = this;
返回新的Promise(resolve => {
self.req = {key: value}
resolve();
})
}

const y = function(){
const self = this;
return new Promise((resolve,reject)=> {
console.log(self);
reject();
})
}

const z = function(){
const self = this;
返回新的Promise((resolve,reject)==> {
console.log('failed');
})
}



pro([x,y,z])
.then((self)=> {
console.log('final',self);
})
.catch(e => {
console.log('error',e);
})

x,y,z 是在函数 pro中链接在一起的三个函数
x 成功解析后, y 被执行但被拒绝。



我想停止 z 的执行,因为继续执行毫无意义,并可能在实际代码中产生错误。 / p>

此外,如果有人可以向我推荐此代码的更好版本:

  .then(()=> {
if(i ===(length-1))
resolve();
})

注意:我不能使用 await ,因为此代码将在服务器端执行并且使用 await 可能会阻止其他传入请求

解决方案

使用 async / await 语法:

 异步函数pro(arr){
const self = {req:{},res:{ }};
for(arr的常量f)等待f.call(自身);
返回自我;
}

 异步函数pro(arr){const self = {req:{},res:{}}; for(arr的常量f)等待f.call(自身); return self;} const x = function(){const self = this;返回新的Promise(resolve => {self.req = {key: value} resolve();})} const y = function(){const self = this;返回新的Promise((resolve,reject)=> {console.log(self); reject( y failed);})} const z = function(){const self = this;返回新的Promise((resolve,reject)=> {console.log('failed');})} pro([x,y,z])。then((self)=> {console.log(' final',self);})。catch(e => {console.log('error',e);});  


I am working on a promise chain that was inspired by this answer: https://stackoverflow.com/a/44955506/7485805

I want to break this for loop in order to properly handle the rejection of the chain. I just figured that I can't use break inside the .catch method of the chain.

Here's my code if it helps:

function pro (arr) {
  let chain = Promise.resolve();
  const self = {req: {}, res: {}};
  const length = arr.length;

  return new Promise((resolve, reject) => {
    for(let i=0; i<length; i++){
      chain = chain
          .then(() => arr[i].call(self) )
          .then(() => {
            if(i === (length - 1) )
              resolve();
          })
          .catch(e => {
            reject(e);
          })
    }
  })
  .then(() => {
    return self
  })
  .catch(e => {
    throw new Error (e);
  })

}

const x = function () {
  const self = this;
  return new Promise(resolve => {
    self.req = {key: "value"}
    resolve();
  })  
}

const y =  function () {
  const self = this;
  return new Promise((resolve, reject) => {
    console.log(self);
    reject();
  })
}

const z = function () {
  const self = this;
  return new Promise((resolve, reject) => {
    console.log('failed');
  })
}



pro([x, y, z])
.then((self) => {
  console.log('final',self);
})
.catch(e => {
  console.log('error', e);
})

x, y, z are three functions chained together in function pro While, x resolves successfully, y is executed but gets rejected.

I want to stop the execution of z since it's pointless to continue and may produce error in actual code.

Also, if someone can recommend me a better version for this piece of code:

.then(() => {
  if(i === (length - 1) )
    resolve();
})

Note: I cannot use await since this code will be executed server-side and use of await may block other incoming requests.

解决方案

It is much easier to do with the async/await syntax:

async function pro(arr) {
    const self = {req: {}, res: {}};
    for(const f of arr) await f.call(self);
    return self;
}

async function pro(arr) {
    const self = {req: {}, res: {}};
    for(const f of arr) await f.call(self);
    return self;
}

const x = function () {
  const self = this;
  return new Promise(resolve => {
    self.req = {key: "value"}
    resolve();
  })  
}

const y =  function () {
  const self = this;
  return new Promise((resolve, reject) => {
    console.log(self);
    reject("y failed");
  })
}

const z = function () {
  const self = this;
  return new Promise((resolve, reject) => {
  	console.log('failed');
  })
}

pro([x, y, z]).then((self) => {
  console.log('final',self);
})
.catch(e => {
  console.log('error', e);
});

这篇关于在for循环中打破Promise链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆