等待和异步回调地狱

时间:2017-04-07 00:14:02

标签: promise async-await ecmascript-2017

我想让UserDataGenerator类像传统的SYNC类一样工作。

我的期望是userData.outputStructure可以为我准备好数据。

let userData = new UserDataGenerator(dslContent)
userData.outputStructure

getFieldDescribe(this.inputStructure.tableName, field)是一个调用Axios.get

的ASYNC调用

以下是我目前的进展情况,但在我打印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
    }

}

1 个答案:

答案 0 :(得分:0)

您正在尝试使用await数组,但这些数组无法正常运行。在处理promises数组时,您仍需要使用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)
            })
        ))]
    };
}