有个关于异步的问题请教一下
发布于 6 年前 作者 BryanChiao 1971 次浏览 来自 问答

代码:

// create.ts
export function create() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      console.log('create');
      res('123');
    }, 3000);
  });
}

// getInstance.ts
let instance = null;
export async function getInstance() {
  if (!instance) {
    instance = await create();
  }
  return instance;
}

// test.ts
async function one() {
  const o = await getInstance();
  console.log(o);
}

async function two() {
  const t = await getInstance();
  console.log(t);
}

one();
two();

执行结果如下

create
create
123
123

请教一下如何修改getInstance.ts才能让create只执行一遍

5 回复

执行one()、two()之间是异步的,两个方法都会在instance = await create();的时候阻塞,可是这时getInstance()方法已被调用,所以create()会执行两次 one()、two()是async函数,执行的时候使用await就可以了

@dingyuanwu 这边为了测试才用的one two 实际上是在两个不同地方用了await getInstance() 所以在考虑能不能通过修改instance.ts实现

@BryanChiao 你需要了解的是单例模式,而不是异步。

来自MaterialCNode

直接return singleton promise

// getInstance.ts
let instance = null;
export async function getInstance() {
  if (!instance) {
    instance = create();
  }
  return instance;
}

@huhu2356 问题解决了 谢谢

回到顶部