【发布时间】:2020-07-04 22:04:02
【问题描述】:
在尝试询问我的讲师并尝试在网上冲浪后,我并没有真正了解异步/等待方法。我最初认为 async/await 可以为我的活动选择挑战返回所需的结果,但事实并非如此。
根据给出的这段代码,我试图 console.log() 从函数 selectPerformanceByFestivalId 中取出结果,但是当我看到结果时,它只给我一个空对象作为结果,而不是一个对象数组。
按道理我应该得到这样的东西:
[
{
"performanceid": "1234567890",
"starttime": 1330,
"endtime": 1530,
"festivalid": "2234567891"
},
{
"performanceid": "1234567891",
"starttime": 1530,
"endtime": 1630,
"festivalid": "2234567891"
},
{
"performanceid": "1234567892",
"starttime": 1330,
"endtime": 1530,
"festivalid": "2234567891"
},
{
"performanceid": "1234567893",
"starttime": 1330,
"endtime": 1530,
"festivalid": "2234567891"
},
{
"performanceid": "1234567894",
"starttime": 1430,
"endtime": 1530,
"festivalid": "2234567891"
}
]
但我得到了这个结果:{}。
这是我当前的异步/等待代码:
async function sortPerformanceByFinishTime(endTime) {
const filteredPerformance = await selectPerformanceByFestivalId; //do a await to let the previous function execute first before continuing
const storeArray = [] //create a new array to reorder the stuff again
console.log(filteredPerformance);
};
这就是我的selectPerformanceByFestivalId:
// 1. selectPerformance to correctly select set of performance for computation
function selectPerformanceByFestivalId(performances) {
const l = performances.length; //length of performances
const selectedPerformance = []; //create a new array selectedPerformance
for (let i = 0; i < l; i++) { //iterate through all the festivalId
selectedPerformance.push(performances[i]); //push filtered performance into the array
};
return selectedPerformance; //return the array
};
selectPerformanceByFestivalId 应该保存整个 json 结果(即上面的数据),当我 console.log(filteredPerformance) 时,我希望得到相同的 json 结果。
有什么问题吗?
【问题讨论】:
-
请分享
selectPerformanceByFestivalId方法的代码。 -
嗨。我已经编辑了我的帖子。谢谢你的提示!
-
如果你在等待
selectPerformanceByFestivalId方法,它需要被标记为异步并且必须返回一个promise。可以在 URL javascript.info/async-await 找到一个示例 -
您的代码中没有任何异步内容,因此您不应该使用
async/await。此外,您需要调用selectPerformanceByFestivalId并传递一个参数。 -
几件事。 1. selectPerformanceByFestivalId 好像是在做同步计算,await有什么具体原因吗? 2. 你不是在调用它,你只是在引用它