Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4. 实现Primise.race #4

Open
Sunny-117 opened this issue Nov 3, 2022 · 4 comments
Open

4. 实现Primise.race #4

Sunny-117 opened this issue Nov 3, 2022 · 4 comments

Comments

@Sunny-117
Copy link
Owner

/**
   * 返回的Promise与第一个有结果的一致
   * @param {iterator} proms
   */
  Promise.race=function(proms) {
    return new MyPromise((resolve, reject) => {
      for (const p of proms) {
        MyPromise.resolve(p).then(resolve, reject);
      }
    });
  }
@lxy-Jason
Copy link
Contributor

Promise.myRace = function(arr){
  return new Promise((resolve,reject) => {
    for(let item of arr){
      Promise.resolve(item).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    }
  })
}
let p1 = new Promise(resolve => {
  setTimeout(() => {
    resolve(1)
  },100)
})
let p2 = new Promise((resolve,reject) => {
  setTimeout(() => {
    reject(2)
  })
})
let p3 = new Promise((resolve,reject) => {
  setTimeout(() => {
    resolve(3)
  })
})

Promise.myRace([p1,p2,p3]).then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
})

@kangkang123269
Copy link

Promise.race = function(promises) {
  // 检查是否是迭代对象
  if(typeof promises[Symbol.iterator] !== 'function') {
      throw(`传入的参数不是一个可迭代对象`)
  }
  return new Promise(function(resolve, reject) {
    for (var i = 0; i < promises.length; i++) {
      Promise.resolve(promises[i]).then(resolve, reject);
    }
  });
}

@zcxiaobao
Copy link

Promise.race = function (promises) {
  if (promises == null || typeof promises[Symbol.iterator] !== "function") {
    throw new Error(`传入的参数不是可迭代对象`);
  }
  promises = [...promises];
  return new Promise((resolve, reject) => {
    for (let p of promises) {
      Promise.resolve(p).then(resolve).catch(reject);
    }
  });
};

@Windseek
Copy link

Windseek commented Nov 8, 2024

const race = (promises) => {
  return new Promise((resolve, reject) => {
    promises.forEach(item => {
      item.then(resolve).catch(reject);
    })
  })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants