【发布时间】:2021-10-26 01:46:18
【问题描述】:
promise 创建一个像这样的数组,取自控制台:
(6) [Promise, Promise, Promise, Promise, Promise, Promise]
0: Promise {<fulfilled>: undefined}
1: Promise {<fulfilled>: undefined}
2: Promise {<fulfilled>: undefined}
3: Promise {<fulfilled>: undefined}
4: Promise {<rejected>: SyntaxError: Unexpected token < in JSON at position 0}
5: Promise {<fulfilled>: undefined}
length: 6
无法使用。
代码是这样的:
export default async function getData() {
let response = await request('http://localhost:2000/api/ves.json').then((data) => fetch(data));
let store = await response.json();
let list = await store.map(async (input, index)=>{
let details = await request(`http://localhost:2000/api/${input.id}.json`).then((data) => fetch(data));
let foo = await details.json();
console.log(foo);
input = await {...input, ...foo};
});
return list;
}
此时,返回列表(使用 useData 函数时)映射似乎还没有完成。所以它返回“promise”而不是它应该返回的列表。
目的是组合对象。这不是通过使用来自第一个对象(在对象数组中)的信息来从第二个对象获取信息。然后将第二个对象推入第一个对象,在数组中的同一点检索信息以获得第二个对象。
如果我也这样做,也会出现同样的问题
input = await {...input, ...foo};
}});
await Promise.all(list)
return list;
或
console.log(foo);
input = await {...input, ...foo};
}});
let fish = await Promise.all(list)
return fish;
给出控制台错误
(6) [undefined, undefined, undefined, undefined, undefined, undefined]
这个useData函数是通过这个在react页面中调用的。
const [ves] = useData();
useEffect(()=>{
console.log(ves);
},[ves])
【问题讨论】:
-
await Promise.all(list)应该等待映射数组中的所有 Promise。 -
替换“返回列表;” with let newList = await Promise.all(list) return newList;有同样的问题
标签: javascript reactjs asynchronous fetch-api