如何在JavaScript/TypeScript中编写更简洁的两阶段承诺?
P粉401527045
P粉401527045 2024-02-25 22:20:55
0
1
409

我这里的用例:

  • 如果资源立即可用,则返回它
  • 如果资源尚不可用,则显示模式或加载指示器,然后等待其准备就绪
  • 模态逻辑必须与承诺/请求逻辑解耦

有更好的设计模式吗?

let twoStagePromise = (state: boolean): Promise<{ ready: boolean, wait: Promise<any>; }> => {
    return new Promise((resolve, reject) => {
        try {
            if (state) {
                resolve({
                    ready: true,
                    wait: new Promise((resolve, reject) => {
                        resolve([1, 2, 3]);
                    })
                });
            } else {
                resolve({
                    ready: false,
                    wait: new Promise((resolve, reject) => {
                        setTimeout(() => { resolve([1, 2, 3]); }, 1000);
                    })
                });
            }
        } catch (e) {
            reject(e);
        }
    });
};

twoStagePromise(false).then((data) => {
    if (!data.ready) {
        console.log('loading...');
    }
    return data.wait;
}).then((result) => {
    console.log("recieved result", result);
}).catch((error) => {
    console.log("try-catch failed or inner promise failed")
});

阅读了一些评论后,我大大简化了代码:

let twoStagePromise = (state: boolean): Promise<number[] | Promise<number[]>> => {
    return new Promise((resolve, reject) => {
        try {
            if (state) {
                resolve([1, 2, 3]);
            } else {
                resolve(new Promise((resolve) => setTimeout(() => { resolve([1,2,3])  }, 1000)))
            }
        } catch (e) {
            reject(e);
        }
    });
};

twoStagePromise(false).then((dataOrPromise) => {
    if (dataOrPromise instanceof Promise) {
        console.log('loading...');
    }
    return dataOrPromise // continue the promise chain by returning the promise or data
}).then((result) => {
    console.log("recieved result", result);
}).catch((error) => {
    console.log("try-catch failed or inner promise failed", error)
});

P粉401527045
P粉401527045

全部回复(1)
P粉270842688

您可以创建一个显式返回值或其承诺的函数。无论如何你都可以轻松地 await 了。要检查结果是否同步,请使用 result instanceof Promise

type Awaitable = T | Promise
function maybeImmediate(
    call: () => Awaitable,
    tryImmediate: boolean,
): Awaitable {
    if (tryImmediate) {
        try {
            return call(); // you don't know if it's T or Promise actually
        } catch (err) {
            // choose the one you want
            if (Math.random() > 0.5) {
                throw err;
            } else {
                return Promise.reject(err)
            }
        }
    } else {
        // make sure it's a promise
        return Promise.resolve().then(() => call())
    }
};

let cache: Record = {};
function getCached(url: string): Awaitable {
    if (cache[url]) return cache[url];
    return new Promise(r => {
        setTimeout(() => r('result of ' + url), 1000)
    }).then(v => { cache[url] = v; return v })
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板