mobx 商店中的承诺

Promises in a mobx store

我不确定如何在我的 mobx 商店中实现承诺。我想在一个循环中按顺序 运行 执行两个操作,并确保在 运行 完成第二个操作之前等待第一个操作完成。这是我的商店代码的示例。请要求任何进一步的说明,我一定会添加它。我试图将代码简化为我认为找到解决方案所必需的代码。谢谢!

import { observable, action } from 'mobx';

import Store from '../support/store';

class Upload extends Store {
  @observable fileList = null;  // array of files to be uploaded
  @observable processedFile = null;  // single file pre-processed for upload

  @action processFile(file) {
    // takes file from fileList array, 'processes' it and 
    // places the result in this.processedFile
  }

  @action post() {
    // makes a POST request, uploading this.processedFile
    // sets this.processedFile = null
  }

  @action postFileList() {
    // loops over the array this.fileList
    // runs this.processFile(file)
    // waits until processFile(file) is finished
    // runs post()
    // waits until post() is finished
    // removes file from the this.fileList array
  }
}

如果你在动作中做一些异步的事情,你需要确保wrap the asynchronously called function in an action as well

您可以创建一个递归 postFileList,当 fileList 中没有更多文件时退出。

例子

class Upload extends Store {
  @observable fileList = [];
  @observable processedFile = null;

  @action processFile(file) {
    return new Promise(resolve => {
      const file = this.fileList[0];
      setTimeout(action(() => {
        this.processedFile = file.processed;
        resolve();
      }), 1000); 
    });
  }

  @action post() {
    return new Promise(resolve => {
      const file = this.processedFile;
      setTimeout(action(() => {
        this.processedFile = null;
        resolve();
      }), 1000); 
    });
  }

  @action postFileList() {
    if (this.fileList.length === 0) {
      return;
    }
    this.processFile()
      .then(() => this.post())
      .then(action(() => {
        this.fileList.shift();
        this.postFileList();
      }));
  }
}