2017-04-07 138 views
0

我想使UserDataGenerator類像傳統的SYNC類一樣工作。等待和異步回調地獄

我的期望是userData.outputStructure可以給我準備的數據。

let userData = new UserDataGenerator(dslContent) 
userData.outputStructure 

getFieldDescribe(this.inputStructure.tableName, field)是一個異步調用,它調用Axios.get

下面是我目前的進展,但它仍然沒有等待數據準備好,當我打印出來的userData.outputStructure

出口默認類UserDataGenerator { inputStructure = null; outputStructure = null; fieldDescribeRecords = [];

constructor(dslContent) { 

    this.outputStructure = Object.assign({}, dslContent, initSections) 
    process() 
} 

async process() { 
    await this.processSectionList() 
    return this.outputStructure 
} 

async processSectionList() { 
    await this.inputStructure.sections.map(section => { 
     this.outputStructure.sections.push(this.processSection(section)); 
    }) 
} 

async processSection(section) { 
    let outputSection = { 
     name: null, 
     fields: [] 
    } 
    let outputFields = await section.fields.map(async(inputField) => { 
     return await this._processField(inputField).catch(e => { 
      throw new SchemaError(e, this.inputStructure.tableName, inputField) 
     }) 
    }) 
    outputSection.fields.push(outputFields) 
    return outputSection 
} 

async _processField(field) { 
    let resp = await ai 
    switch (typeof field) { 
     case 'string': 
      let normalizedDescribe = getNormalizedFieldDescribe(resp.data) 
      return new FieldGenerator(normalizedDescribe, field).outputFieldStructure 
    } 

} 
+0

您不能同步的東西,如果它是異步。你的'process'函數返回一個promise,所以在你記錄'outputStructure'之前需要等待它。 – loganfsmyth

+0

就我而言,我如何將我的課程修改爲承諾課程/功能?謝謝 – newBike

+0

你可以做'userData.process()。then(data => console.log(data))''。沒有辦法等待構造函數內的東西。 – loganfsmyth

回答

0

您正在嘗試使用await陣列,該陣列不像您期望的那樣工作。處理承諾數組時,您仍然需要使用Promise.all,然後才能使用await它 - 就像您不能在數組上連接.then一樣。

那麼你的方法應該是這樣的:

async processSectionList() { 
    const sections = await Promise.all(this.inputStructure.sections.map(section => 
     this.processSection(section) 
    )); 
    this.outputStructure.sections.push(...sections); 
} 

async processSection(section) { 
    return { 
     name: null, 
     fields: [await Promise.all(section.fields.map(inputField => 
      this._processField(inputField).catch(e => { 
       throw new SchemaError(e, this.inputStructure.tableName, inputField) 
      }) 
     ))] 
    }; 
}