javascript - 将 Yummly API 模块输出保存到 Node.JS 中的数组而不是 Console.Log

标签 javascript node.js

我刚刚开始使用 javascript 和 node.js,所以这可能是基础的。我想要做的是将 Yummly 查询的输出保存到变量中。最好是数组或列表。最终是一本字典,但现在我只需要在基本概念上取得进展,我就可以弄清楚其余的事情。

模块工作并且数据正确输出到控制台,但我无法将其保存到任何类型的变量。我已经在这种有限大小格式的程序允许的位置尝试了推送和连接。

有人可以解释或演示如何将 Yummly 查询的输出保存到数组或列表而不是控制台吗?

如果可能的话,您能否解释一下为什么它不能像现在写的那样工作?名称是一个全局的新全局数组,并且每个配方名称都在内循环中推送到它?

附注我主要是一名尝试跳跃的 Python 程序员,因此我们将不胜感激额外的信息。

const Yummly = require('ws-yummly');
    Yummly.config({
            app_key: 'KEY GOES HERE',
            app_id: 'ID GOES HERE'
    });

    const names = new Array();
    Yummly.query('chicken')
            .maxTotalTimeInSeconds(1400)
            .maxResults(20)
            .minRating(3)
            .get()
            .then(function(resp){
                    resp.matches.forEach(function(recipe){
                            console.log(recipe.recipeName);
                            names.push(recipe.recipeName);
                    });
            });
    console.log(names);

最佳答案

短篇故事,您需要等待查询完成。 这是一个工作示例。

const Yummly = require('ws-yummly');
Yummly.config({
    app_key: 'KEY GOES HERE',
    app_id: 'ID GOES HERE'
});

async function main () {
    const resp = await Yummly.query('chicken')
        .maxTotalTimeInSeconds(1400)
        .maxResults(20)
        .minRating(3)
        .get();
    const names = resp.matches.map(recipe => recipe.recipeName);
    console.log(names);
}

main().catch(error => console.error(error))

你的代码也是等效的

const Yummly = require('ws-yummly');
Yummly.config({
        app_key: 'KEY GOES HERE',
        app_id: 'ID GOES HERE'
});

const names = new Array();
console.log(names);
Yummly.query('chicken')
        .maxTotalTimeInSeconds(1400)
        .maxResults(20)
        .minRating(3)
        .get()
        .then(function(resp){
                resp.matches.forEach(function(recipe){
                        console.log(recipe.recipeName);
                        names.push(recipe.recipeName);
                });
        });

因为.then发生在网络请求之后。

修复方法是使用 async/await。

关于javascript - 将 Yummly API 模块输出保存到 Node.JS 中的数组而不是 Console.Log,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50091950/

相关文章:

javascript - ECMA双发箭头使用?

javascript - 元素不遵循过滤器 CSS 的语义

javascript - 在 PyCharm 中禁用 React Prop 的自动 {} 插入

javascript - 在测验应用程序中设置计时器

javascript - 在绝对定位的 div 之上垂直居中 div

node.js - 在 Mongoose 中将两个 OR 查询与 AND 组合

mysql - 您应该以多少列制作另一张表?

javascript - DarkSky API - 未处理的拒绝错误 - ReactJS/Axios/Node.js

node.js - 如何使用 phantomjs 作为 npm 包

javascript - 从 websocket 过滤 json 对象/值并打印到控制台日志