javascript – mobx商店中的承诺

我不确定如何在我的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();
      }));
  }
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...