异步函数 returns 空数组
Async function returns empty array
我正在尝试创建一些数据对的矩阵。 fetchDataPair()
是一个 async
函数。
async function fetchData(info_array){
let matrix = []
for(const i of info_array){
let row = []
for (const j of info_array){
if (i != j){
let pair = fetchDataPair(i,j)
row.push(pair)
}else{
row.push(null)
}
}
Promise.all(row).then((resolvedRow)=>{ //resolve all the promises in the row, then push to matrix
matrix.push(resolvedRow)
})
}
//matrix should be an array of arrays of (resolved) promises, but it just returns an empty array
console.log(matrix) //logs []
return matrix
}
不幸的是,这段代码似乎在行被推入数组之前到达 return matrix
,但我不明白为什么。
谢谢
编辑:将内部函数的名称从 fetchData
固定为 fetchDataPair
代码中有几个错误。
问题是您需要等待 Promise.all。如果您使用 .then,您订阅的是在它完成时收到通知,但执行仍在继续,并且在 promise 完成执行之前会打印控制台。
async function fetchData(info_array){
let matrix = [];
for(const i of info_array){
let row = []
for (const j of info_array){
if (i != j){
let pair = fetchData(i,j)
row.push(pair)
}
else {
row.push(null);
}
}
const rowProc = await Promise.all(row);
matrix.push(rowProc);
}
console.log(matrix)
return matrix
}
//resolve all the promises in the row, then push to matrix
这与等待 pair
promise 解析并将其结果推送到 row
数组的问题完全相同 - 你不能那样做,你需要创建一个数组承诺和使用 Promise.all
:
function fetchData(info_array) {
let matrix = []
for (const i of info_array) {
let row = []
for (const j of info_array) {
if (i != j) {
let pair = fetchDataPair(i,j)
row.push(pair)
} else {
row.push(null)
}
}
matrix.push(Promise.all(row))
// ^^^^^^^^^^^^ ^
}
return Promise.all(matrix)
// ^^^^^^^^^^^
}
我正在尝试创建一些数据对的矩阵。 fetchDataPair()
是一个 async
函数。
async function fetchData(info_array){
let matrix = []
for(const i of info_array){
let row = []
for (const j of info_array){
if (i != j){
let pair = fetchDataPair(i,j)
row.push(pair)
}else{
row.push(null)
}
}
Promise.all(row).then((resolvedRow)=>{ //resolve all the promises in the row, then push to matrix
matrix.push(resolvedRow)
})
}
//matrix should be an array of arrays of (resolved) promises, but it just returns an empty array
console.log(matrix) //logs []
return matrix
}
不幸的是,这段代码似乎在行被推入数组之前到达 return matrix
,但我不明白为什么。
谢谢
编辑:将内部函数的名称从 fetchData
固定为 fetchDataPair
代码中有几个错误。 问题是您需要等待 Promise.all。如果您使用 .then,您订阅的是在它完成时收到通知,但执行仍在继续,并且在 promise 完成执行之前会打印控制台。
async function fetchData(info_array){
let matrix = [];
for(const i of info_array){
let row = []
for (const j of info_array){
if (i != j){
let pair = fetchData(i,j)
row.push(pair)
}
else {
row.push(null);
}
}
const rowProc = await Promise.all(row);
matrix.push(rowProc);
}
console.log(matrix)
return matrix
}
//resolve all the promises in the row, then push to matrix
这与等待 pair
promise 解析并将其结果推送到 row
数组的问题完全相同 - 你不能那样做,你需要创建一个数组承诺和使用 Promise.all
:
function fetchData(info_array) {
let matrix = []
for (const i of info_array) {
let row = []
for (const j of info_array) {
if (i != j) {
let pair = fetchDataPair(i,j)
row.push(pair)
} else {
row.push(null)
}
}
matrix.push(Promise.all(row))
// ^^^^^^^^^^^^ ^
}
return Promise.all(matrix)
// ^^^^^^^^^^^
}