【发布时间】:2020-01-06 12:23:41
【问题描述】:
我需要实现一个异步单例,它创建一个需要异步操作的类的单个实例,以便将参数传递给构造函数。 我有以下代码:
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 被拒绝,则对 getAsyncCompInstance() 的下一次调用将返回未完成的 promise 对象,这意味着将无法重试该对象的创建。
我该如何解决这个问题?
【问题讨论】:
-
我没有看到任何理由,如果承诺被正确拒绝,它应该可以工作。我们也可以检查
someAsyncFunction吗? -
@sjahan 即使 promise 被拒绝,asyncCompInstance 也不再为 null,因此 getAsyncCompInstance() 会返回它而不是继续调用 createAsyncInstance() 的下一行
-
如果
someAsyncFunction抛出错误,则不会执行下一行,因此不会返回任何实例。您可以在静态方法中放置一个 try catch 并在出现错误时返回 null。 -
@AshishModi,这不准确。 getAsyncCompInstance() 不会等待 createAsyncInstance(),它会立即返回 Promise。调用 getAsyncCompInstance() 的代码负责错误处理,如果 getAsyncCompInstance() 抛出/拒绝,此代码将捕获它。
-
我的错。完全错过了“不等待”的部分。
标签: javascript node.js asynchronous async-await singleton