【发布时间】:2020-06-14 02:33:52
【问题描述】:
我在 node.js 中有一个函数,我从中向 url 发出 fetch 请求并从 fetch 获取响应数据,我想将此响应数据用作函数的返回类型。
谁能帮我解决这个问题?我对 node.js 和这整个承诺的事情都很陌生。请帮帮我
app.intent('get train number',(conv,{number})=>{
var result;
let data = fetch("https://myapp.herokuapp.com/status/number/yesterday")
.then(response => response.json())
.then(jsondata=> {
result = jsondata.data;
console.log(result); //this prints the required result well
});
return conv.close('The status of train number'+number+'is'+result);
});
我想这样做。如果我的问题没有意义,请不要低估这个问题(或)。而是让我知道我错在哪里
完整代码:-
'use strict';
const express = require('express');
const {dialogflow} = require('actions-on-google');
const bodyParser = require('body-parser')
const port = process.env.PORT || 3000;
const app = dialogflow({debug:true});
const fetch = require('node-fetch');
app.intent('Default Welcome Intent', (conv)=>{
conv.ask('Hello world!!');
});
app.intent('get train number',(conv,{number})=>{
var result = number;
let data = fetch("https://myapp.herokuapp.com/status/02723/yesterday")
.then(response => response.json())
.then(jsondata=> {
result = jsondata.data;
console.log(result);
});
return conv.close('The status of train number'+number+'is'+result);
});
const expressApp = express().use(bodyParser.json());
expressApp.post('/webhook',app);
expressApp.listen(port);
我正在使用 Node.js
【问题讨论】:
-
您需要在具有
then有效负载的then处理程序中调用conv.close,您不能以您的方式从Promise返回内容思考 - 异步调用不是那样工作的。 -
@AlonEitan 感谢您的建议。我知道我们可以通过回调访问该结果,但我想要的是从我的代码中的 app.intent 函数返回该结果,我不明白如何做到这一点
-
@desusaivenkat 如果是这种情况,那么
app.intent的回调必须支持异步调用或能够传递Promise作为第二个参数。知道app.intent到底是什么会很有用。 -
@goto1 实际上,我正在为对话流代理编写一个 webhook,当有人在我的对话流代理中触发获取列车号意图时,app.intent('get train number') 会被调用跨度>
-
这仍然不能帮助我理解
app.intent支持什么,什么不支持。app.intent来自哪里?你使用什么框架/库/什么?
标签: javascript node.js asynchronous promise async-await