export default class AsyncUtil {
    /**
     * 执行多个promise,将结果封装成数组,按照promise顺序返回
     * @param promises {Array<Promise>>}
     * @returns {Promise<Array>}
     */
    static all(promises) {
        let len = promises.length,
            res = [];
        let count = len;
        if (len) {
            return new Promise((resolve, reject) => {
                for (let i = 0; i < len; i++) {
                    let promise = promises[i];
                    promise.then(
                        (response) => {
                            res[i] = response;
                            if (!--count) {
                                resolve(res);
                            }
                        },
                        (error) => {
                            res[i] = error;
                            if (!--count) {
                                resolve(res);
                            }
                        },
                    );
                }
            });
        }
    }

    /**
     * 延迟指定毫秒数
     * @param time 毫秒值
     * @returns {Promise<boolean>}  返回一个promise
     */
    static wait(time = 100) {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(true);
            }, time);
        });
    }

    /**
     * 包装异步请求与loading
     * @param promise
     * @param loading  目前这个loading仅仅支持ref(false)模式下的值
     * @returns {Promise<unknown>}
     */
    static loadingWrapper(promise, loading = undefined) {
        return new Promise((resolve, reject) => {
            if (loading) {
                loading.value = true
            }
            promise.then(
                (response) => {
                    resolve(response);
                },
                (error) => {
                    reject(error)
                }).finally(_ => {
                if (loading) {
                    loading.value = false
                }
            })
        })
    }

}
