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

10 个 Ajax 同时发起请求,全部返回展示结果,并且至多允许三次失败 #41

Open
TieMuZhen opened this issue Nov 25, 2021 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

10 个 Ajax 同时发起请求,全部返回展示结果,并且至多允许三次失败,说出设计思路

这个问题相信很多人会第一时间想到Promise.all,但是这个函数有一个局限在于如果失败一次就返回了,直接这样实现会有点问题,需要变通下。以下是不完整代码,着重于思路,有两种实现思路

// 非 Promise 写法
let successCount = 0
let errorCount = 0
let datas = []
ajax(url, (res) => {
    if (success) {
        success++
        if (success + errorCount === 10) {
            console.log(datas)
        } else {
            datas.push(res.data)
        }
    } else {
        errorCount++
        if (errorCount > 3) {
            // 失败次数大于3次就应该报错了
            throw Error('失败三次')
        }
    }
})

// Promise 写法
let errorCount = 0
let p = new Promise((resolve, reject) => {
    if (success) {
        resolve(res.data)
    } else {
        errorCount++
        if (errorCount > 3) {
            // 失败次数大于3次就应该报错了
            reject(error)
        } else {
            resolve(error)
        }
    }
})
Promise.all([p]).then(v => {
    console.log(v);
});

参考文章

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