我有一个嵌套的Promise循环,然后结束了一个for循环,该循环将files数组中的项目压入。
public async content() {
let files = [];
return new Promise(async (resolve, reject) => {
await this.axios.get(this.currentRequest).then(async biosample => {
await this.axios.get(this.currentRequest + biosample.data.item).then(async datasets => {
for (let i = 0; i < datasets.data.Items.length; i++) {
await this.axios.get(this.currentRequest + datasets.data.Items[i].Id).then(response => {
files.push(response.data.Item);
}).catch(reason => {
reject(reason)
});
}
})
}).catch(function (error) {
reject(new Error(error.response))
});
resolve(files)
})
}
可以正确进行呼叫,因为如果我使用Promise.all([promises here])
,则可以正常工作。但我正在尝试学习正确地兑现承诺。
当我使用Webstorm调试数据集时,似乎已定义数据集并具有必要的属性。
答案 0 :(得分:3)
示意上,您的代码必须像这样
content() {
return Promise.resolve()
.then(_ => this.axios.get(this.currentRequest)
.then(biosample => this.axios.get(this.currentRequest + biosample.data.item))
.then(datasets => Promise.all(datasets.data.Items.map(item => this.axios.get(this.currentRequest + item.Id))))
}
答案 1 :(得分:2)
您没有利用等待的潜力。您的代码可以很简单:
public async content() {
let files = [];
return new Promise(async (resolve, reject) => {
try {
let biosample = await this.axios.get(this.currentRequest)
let datasets = await this.axios.get(this.currentRequest + biosample.data.item)
for (let i = 0; i < datasets.data.Items.length; i++) {
let response = await this.axios.get(this.currentRequest + datasets.data.Items[i].Id)
files.push(response.data.Item);
}
resolve(files)
} catch(error) {
reject(new Error(error.response || error))
};
})
}