Javascript mobx商店里的承诺

Javascript mobx商店里的承诺,javascript,asynchronous,promise,es6-promise,mobx,Javascript,Asynchronous,Promise,Es6 Promise,Mobx,我不知道如何在我的mobx商店中实现承诺。我有两个操作要在循环中顺序运行,并确保在运行第二个操作之前等待第一个操作完成。这是我的商店代码的一个例子。请要求进一步澄清,我一定会补充。我试图将代码简化为我认为找到解决方案所必需的内容。谢谢 import { observable, action } from 'mobx'; import Store from '../support/store'; class Upload extends Store { @observable fileLi

我不知道如何在我的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
  }
}

如果在操作中执行异步操作,则需要确保执行

您可以创建一个递归的
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();
      }));
  }
}

processFile
异步还是仅仅
post
?@Tholle
processFile
也是异步的。请使postFileList函数
async
并像以前一样编写代码。mobx的美妙之处在于,您不需要任何特殊的代码就可以工作。