在JavaScript中创建异步单调 [英] Creating an async singletone in javascript

查看:69
本文介绍了在JavaScript中创建异步单调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一个异步单例,该单例创建一个类的单个实例,该实例需要异步操作才能将参数传递给构造函数. 我有以下代码:

I need to implement an async singleton, that creates a single instance of a class that requires asynchronous operations in order to pass arguments to the constructor. I have the following code:

class AsyncComp {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    // A factory method for creating the async instance
    static async createAsyncInstance() {
        const info = await someAsyncFunction();
        return new AsyncComp(info.x, info.y);
    }

    // The singleton method
    static getAsyncCompInstance() {
        if (asyncCompInstance) return asyncCompInstance;
        asyncCompInstance = AsyncComp.createAsyncInstance();
        return asyncCompInstance;
    }
}

只要promise履行,代码似乎就可以正常工作.但是,如果Promise被拒绝,则对getAsyncCompInstance()的下一次调用将返回未实现的Promise对象,这意味着将无法重试该对象的创建. 我该如何解决?

The code seems to work fine, as long as the promise fulfils. If, however, the promise is rejected the next calls to getAsyncCompInstance() will return the unfulfilled promise object, which means that it will not be possible to retry the creation of the object. How can I solve this?

推荐答案

因此,在考虑了几种可能的解决方案之后,我决定使用try/catch块将异步调用包装在createAsyncInstance()中,如果失败,将asyncCompInstance设置为null,并抛出发生的错误.这样,如果对象创建失败,则调用方可以再次调用getAsyncCompInstance()尝试获取该类的实例:

So after thinking about a couple of possible solution, I decided to wrap the asynchronous call in createAsyncInstance() with a try/catch block, and if it failed, set asyncCompInstance back to be null, and throw the error the occurred. This way, if the object creation failed, the caller can call getAsyncCompInstance() again to try to get an instance of the class:

class AsyncComp {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    // A factory method for creating the async instance
    static async createAsyncInstance() {
        try {
            const info = await someAsyncFunction();
            return new AsyncComp(info.x, info.y);
        }
        catch (err) {
            asyncCompInstance = null;
            throw err;
        }
    }

    // The singleton method
    static getAsyncCompInstance() {
        if (asyncCompInstance) return asyncCompInstance;
        asyncCompInstance = AsyncComp.createAsyncInstance();
        return asyncCompInstance;
    }
}

我知道这不是最干净的代码,尤其不是经典的工厂模式实现,但这是我目前能想到的最好的代码.很想听听对此解决方案的意见/建议.

I know this is not the cleanest code, and specifically not the classic factory pattern implementation, but this is the best I could come up with at the moment. Would love to hear comments/suggestions on this solution.

这篇关于在JavaScript中创建异步单调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆