首页 > 解决方案 > 在 for 循环中打破 Promise 链

问题描述

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

我想打破这个 for 循环,以便正确处理链的拒绝。我只是想我不能在链break的方法中使用。.catch

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

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, zpro 是在函数While中链接在一起的三个函数,x成功解析,y执行但被拒绝。

我想停止执行,z因为继续没有意义,并且可能在实际代码中产生错误。

另外,如果有人可以为这段代码推荐一个更好的版本:

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

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

标签: javascriptfor-loopes6-promise

解决方案


async/await使用语法要容易得多:

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);
});


推荐阅读