在 Alexa Lamda Intent 处理程序中实现 fetch

问题描述 投票:0回答:1

我正在尝试在意图处理程序中使用 Node JS 中的本机 fetch 命令。我在等待子句中遇到语法错误。我需要做什么来实现这个干净的 http 调用?

const fetch = require('node-fetch')
        await fetch('https://api.weather.gov/points/38.8894,-77.0352')
        .then(res => res.json());

代码执行时无需等待,但响应不会等待 fetch 完成。

alexa-skills-kit
1个回答
0
投票

首先,您是否将处理程序声明为异步函数?当函数包含await 子句时,您必须执行此操作。 其次,我会放弃 .then 处理,执行以下操作会更干净:

// Handler declared as async, required for functions with an await

async handle(handlerInput) {
        
const fetch = require('node-fetch')
const res = await fetch('https://api.weather.gov/points/38.8894,-77.0352');
const obj = await res.json();

// Do with obj whatever you want.
 

}
© www.soinside.com 2019 - 2024. All rights reserved.