首页 > 解决方案 > 生成器函数中的多次提取

问题描述

当我试图学习如何使用生成器函数时,我遇到了使用它来运行多个提取的问题。

我正在尝试做的事情:
我正在尝试使用 Hackernews API 来获取新闻故事,然后使用响应中给出的 id 从同一个 API 获取评论。

输出:
{ value: Promise { }, done: false }
TypeError: Cannot read property 'kids' of undefined at getFirstComment (C:\Users\madsn\Documents\dev\generatorfunctions\fetchingInterTwice.js:13:29) at getFirstComment。 runThroughIt (C:\Users\madsn\Documents\dev\generatorfunctions\fetchingInterTwice.js:31:35) 处的 next () 在 processTicksAndRejections (internal/process/task_queues.js:93:5)
{ value: undefined, done: true }
{ 值:未定义,完成:真 }

代码:

const fetch = require("node-fetch")


function requestStuff(url) { ///simple request
    return fetch(url).then(respJson => respJson.json()).catch(err => console.log(err));
}

function* getFirstComment() {
    try {

        //gets the story and the comments id(kids of type array)
        var result1 = yield requestStuff("https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty")
        var resID = result1.kids[0];

        //gets the comment-text given the comment-id
        var result2 = yield requestStuff("https://hacker-news.firebaseio.com/v0/item/" + resID + ".json?print=pretty")
        var resText = result2.text

        console.log(resText.text)

    } catch (error) {
        console.log(error)
    }
}

let main = getFirstComment()

async function runThroughIt(generator) {
    let stepOne = await generator.next()
    console.log(stepOne)
    let stepTwo = await generator.next()
    console.log(stepTwo)
    let stepThree = await generator.next()
    console.log(stepThree)

}

runThroughIt(main)

如果您有修复或解释此文章的链接,请提前致谢!

标签: javascriptnode.jsfunctionasynchronousfetch

解决方案


以下是您的代码的问题:

您的requestStuff函数应该是async并且返回值应该是网络请求的评估结果。目前,您只是返回 Promise 对象。

yieldfetch表达式的结果分配给.result1

这是您可以解决的方法:

const fetch = require("node-fetch")


async function requestStuff(url) { ///simple request
    const res = await fetch(url)
      .then(respJson => respJson.json())
      .catch(err => console.log(err));

  return res;

}

async function* getFirstComment() {
    try {

        //gets the story and the comments id(kids of type array)
        var result1 = await requestStuff("https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty");

      yield result1;

      var resID = result1.kids[0];


        //gets the comment-text given the comment-id
        var result2 = await requestStuff("https://hacker-news.firebaseio.com/v0/item/" + resID + ".json?print=pretty")
        var resText = result2.text

        console.log(resText.text)

      yield resText;

    } catch (error) {
        console.log(error)
    }
}

let main = getFirstComment()

async function runThroughIt(generator) {
    let stepOne = await generator.next();
    console.log("res from step 1! ", stepOne);
    let stepTwo = await generator.next()
    console.log("res from step 2: ", stepTwo);

  //will return undefined because the function has finished evaluating!
    let stepThree = await generator.next()
    console.log(stepThree)

}

runThroughIt(main)

以上有效!现在特别注意在我的示例中调用yield,awaitasync关键字的位置,并将其与您在代码中调用它的位置进行比较!


推荐阅读