等待和异步回调地狱
问题描述:
我想使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
}
}
答
您正在尝试使用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)
})
))]
};
}
您不能同步的东西,如果它是异步。你的'process'函数返回一个promise,所以在你记录'outputStructure'之前需要等待它。 – loganfsmyth
就我而言,我如何将我的课程修改为承诺课程/功能?谢谢 – newBike
你可以做'userData.process()。then(data => console.log(data))''。没有办法等待构造函数内的东西。 – loganfsmyth