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

手写Promise.race #94

Open
Twlig opened this issue Apr 13, 2022 · 0 comments
Open

手写Promise.race #94

Twlig opened this issue Apr 13, 2022 · 0 comments

Comments

@Twlig
Copy link
Owner

Twlig commented Apr 13, 2022

其实手写Promise.race和all差不多,只不过race是返回完成的第一个Promise的值。还有一个重点在于,要对传入race的参数做一个Promise包装,不然传入的很可能是race([3,5,6])这种数据,这不是promise类型,无法调用then方法。

function race(arr) {
    if(arguments.length > 1) {
        console.log('参数过多')
        return
    }
    return new Promise((resolve, reject) => {
        arr.forEach(item => {
            Promise.resolve(item).then(value => {
                resolve(value)
            }, err => {
                reject(err)
            })
        })
    })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant