简体   繁体   English

等待函数完成,然后再继续使用JavaScript

[英]Wait for a function to finish before continuing in javascript

What I trying to do is to make the save method to wait for this.collection.create() before executing the save because otherwise it might crash. 我想要做的是使save方法在执行保存之前等待this.collection.create() ,因为否则可能会崩溃。

class UserRepository extends BaseRepository<User>
{
    constructor()
    {
        super();

        this.collection = this.db.collection('users');
        this.collection.create().then(res => {
            if (res.code === 200)
            {
                // collection successfully created
            }
        }).catch(err => {
            if (err.code === 409)
            {
                // collection already exists
            }
        });
    }
}

class BaseRepository<T>
{
  protected db: Database = Container.get('db');
  protected collection: DocumentCollection;

  public save(model: T): void
  {
    this.collection.save(model);
  }
}

And then I can use it like this: 然后我可以像这样使用它:

const userRepository = new UserRepository();
userRepository.save(new User('username', 'password'));

I can think of two solutions 我可以想到两种解决方案

  1. Run this.collection.create() synchronously 同步运行this.collection.create()
  2. Create a property called isCollectionReady and make a small loop in save method that wait for isCollectionReady value to change to true. 创建一个名为isCollectionReady的属性,并在save方法中进行一个小循环,等待isCollectionReady值更改为true。

Is there any better way to do that? 有什么更好的方法吗?

Definitely don't use a loop; 绝对不要使用循环; JavaScript is single-threaded, and the async event will never complete. JavaScript是单线程的,并且async事件将永远不会完成。

You can store off the Promise for the initialization instead and simply chain onto it: 您可以存储Promise进行初始化,而只需链接到它即可:

class UserRepository extends BaseRepository<User>
{
    constructor()
    {
        super();

        this.collection = this.db.collection('users');
        this._initPromise = this.collection.create().then(res => {
            if (res.code === 200)
            {
                // collection successfully created
            }
        }).catch(err => {
            if (err.code === 409)
            {
                // collection already exists
            }
        });
    }

    ensureInitialized() {
        return this._initPromise;
    }
}

class BaseRepository<T>
{
  protected db: Database = Container.get('db');
  protected collection: DocumentCollection;

  public ensureInitialized() {
    return Promise.resolve();
  }

  public save(model: T): Promise<void>
  {
    return this.ensureInitialized()
      .then(() => this.collection.save(model));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 javascript-等到功能完成再继续 - javascript- Wait till function finish before continuing 如何继续等待一个功能完成? - How to wait for one function to finish before continuing? 等待一项功能完成后再继续? - Wait for one function to finish before continuing? 我如何让我的 javascript 函数在继续之前等待 WebSql 事务完成 - How i make my javascript function wait to WebSql transactions to finish before continuing 等待函数完成,然后再继续执行$ .each函数中的下一个循环 - wait for the function to finish before continuing to the next loop in a $.each function JavaScript:4个异步函数要依次等待对方完成才能继续? - JavaScript: 4 asyncronys functions to wait for each other sequentially to finish before continuing? 如何让程序在继续使用javascript之前等待if语句完成? - How to make the program wait for the if statement to finish before continuing in javascript? 获取功能以等待后期中间件保存完成后再继续 - Getting a function to wait for a post middleware save to finish before continuing 在继续之前等待一个功能完成的正确方法? - Proper way to wait for one function to finish before continuing? 如何在继续之前等待递归 function 完全完成? - How can I wait for a recursive function to completely finish before continuing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM