【问题标题】:Async/await not returning result at all异步/等待根本不返回结果
【发布时间】: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. 你不是在调用它,你只是在引用它

标签: javascript async-await


【解决方案1】:

您正在提供对函数对象的引用而不是调用它。

将您的代码行更改为

  const filteredPerformance = await selectPerformanceByFestivalId(); 

【讨论】:

  • 这并没有回答几个问题。该函数需要一个未传递的参数。此外,关于如何在调用方方法中获得performances 的问题也不清楚。为什么它必须异步。
【解决方案2】:

我在https://plnkr.co/edit/OeJg8ISk8XHinuR3 创建了一个 Plunk 使用您在上面共享的示例代码。对现有代码进行几处更改。

  1. 在函数selectPerformanceByFestivalId之前添加了async关键字。
  2. 在函数sortPerformanceByFinishTime中调用函数selectPerformanceByFestivalId后添加括号

【讨论】:

    猜你喜欢
    • 2020-02-10
    • 2019-10-20
    • 1970-01-01
    • 2020-12-24
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    相关资源
    最近更新 更多