我刚刚开始使用 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/