【问题标题】:How do i return the response of a fetch as a return type of a function [duplicate]如何将 fetch 的响应作为函数的返回类型返回 [重复]
【发布时间】: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


【解决方案1】:

你可以试试这个,然后把return放在里面:

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);
    });
    });

【讨论】:

  • return 语句在这种情况下没有任何作用。
猜你喜欢
  • 1970-01-01
  • 2015-06-06
  • 2020-11-22
  • 2021-09-09
  • 2019-08-11
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多