-
-
Notifications
You must be signed in to change notification settings - Fork 235
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
Comments
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);
}) |
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);
}
});
} |
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);
}
});
}; |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: