javascript - 将 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);
解决方案
您需要等待查询完成的短篇小说。这是一个工作示例。
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 发生在网络请求之后。
解决方法是使用异步/等待。
推荐阅读
- flutter - 将 2 个变量从 2 个不同的屏幕传递到 1 个屏幕
- apache-spark - 查询“select * from tab1”时在 hive 中找不到表
- r - 子文档中的块选项默认值
- mysql - 导入时未选择数据库
- android-studio - Android Studio 4.0 文件 > 新建 > 活动或片段不起作用
- excel - 根据另一行的最大值有条件地格式化单元格
- r - R:如何去掉字符串中的问号块?
- salesforce-einstein - Einstein:图表字段顺序不同于 SAQL
- java - 由于 setOldSku(String oldSku) 已折旧
- python - 如何读取excel文件并将内容转换为python中的列表列表?