【问题标题】:Why i need to use return keyword in this function so the promise work correctly?为什么我需要在此函数中使用 return 关键字才能使 promise 正常工作?
【发布时间】:2021-02-05 11:36:54
【问题描述】:

代码:

script1.js:

function getPeople(fetch) {
  fetch('some API').then(res => res.json()).then(data => {
     return {
       count: data.count,
       results: data.results
     }

  })
}

module.exports = getPeople;

脚本2:

const fetch = require('node-fetch');
const getPeople = require('./script1');

getPeople(fetch).then(data => console.log(data) //TypeError: Cannot read property 'then' of undefined

getPeople 函数中添加return 关键字时,此错误已解决,如下所示:

function getPeople(fetch) {
  return fetch('some API').then(res => res.json()).then(data => {
     return {
       count: data.count,
       results: data.results
     }

  })
}

我想知道为什么我在 fetch() 之前需要这个 return 关键字,而我已经使用它来返回数据:

 return {
       count: data.count,
       results: data.results
     }

【问题讨论】:

    标签: javascript node.js asynchronous promise


    【解决方案1】:

    如果您没有从 fetch() 创建的函数中返回承诺,那么您的函数只是返回 undefined 并且没有将任何内容传回给调用者。你必须兑现承诺。

    您的数据返回是对.then() 回调的返回。这不是您的功能的回报。该返回也是必需的,因为它设置了父 Promise 的已解析值,但这只是从回调返回到 Promise 基础结构,而不是从您的函数本身返回。要从函数本身返回,您需要一个未嵌套在其他函数中的 return

    【讨论】:

    • 你的意思是我需要返回另一个promise,我需要返回一个promise表达式??
    • @SaherElgendy - 不,请阅读我刚刚添加到答案中的内容。 getPeople() 的第二个实现是正确的方法。在您的第一个实现中,getPeople() 根本没有 return 语句,只有一个用于承诺回调,因此 getPeople() 不会返回任何内容。
    • @SaherElgendy - 在您的情况下,“then”中的“return”语句实际上并没有做任何事情。您可以删除最后一个“then”。您正在接受“计数”并将其放入“计数”中,这是多余的。在“then”内的回调中使用 return 用于格式化输出。你的第二个例子很好,你可以用 return 删除“then”。基本上,return fetch(...).then(res => res.json()) 很好,满足您的所有需求。
    • @LeonardoG - 你无法真正判断内部返回是否有任何作用。 OP 可能只想用许多属性中的两个来解决,或者它可能是多余的。无论如何,在这个讨论的背景下,它并没有伤害任何东西。但是,getPeople() 根本没有返回值是这里的主要问题。
    • @SaherElgendy - 您需要 return 中的 return fetch()... 以便您的 getPeople() 函数返回承诺。如果没有该返回,getPeople() 函数将不会返回任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 2017-12-22
    相关资源
    最近更新 更多