2016-12-13 47 views
3

我不知道如何實現我的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 
    } 
} 
+0

是'processFile'異步或只是'POST'? – Tholle

+0

@Tholle'processFile'也是異步的。 – wuliwong

+0

使postFileList函數'async'完全像您以前寫的那樣編寫代碼。 mobx的美妙之處在於你不需要任何特殊的特定代碼就可以工作。 –

回答

0

如果你異步做一些動作裏面,你需要確保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(); 
     })); 
    } 
}