[英]Saving Yummly API Module Output to Array in Node.JS Instead of Console.Log
我只是从javascript和node.js开始,所以这可能是基本的。 我想做的是将Yummly查询的输出保存到变量中。 优选地,数组或列表。 最终是一本字典,但是现在我只需要在基本概念上取得进展,其余的我就可以搞清楚。
该模块可以正常工作,并且数据可以正确输出到控制台,但是我无法将其保存到任何种类的变量中。 我已经在这种有限大小格式的程序所允许的几乎所有位置尝试了push和concat。
有人可以解释或演示如何将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在网络请求之后发生。
解决方法是使用异步/等待。
据我所知,const变量不能用于重新分配或可变的数据。 相反,您可以尝试:
let names = [];
在foreach循环上:
names = [...names, newArrayValue];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.