首页 > 解决方案 > 将 Yummly API 模块输出保存到 Node.JS 中的数组而不是 Console.Log

问题描述

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

该模块工作正常,数据正确输出到控制台,但我无法将其保存到任何类型的变量中。我已经在这种有限大小格式的程序允许的几乎非常位置尝试了 push 和 concat。

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

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

PS我主要是一名尝试进行跳跃的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);

标签: javascriptnode.js

解决方案


您需要等待查询完成的短篇小说。这是一个工作示例。

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 发生在网络请求之后。

解决方法是使用异步/等待。


推荐阅读