首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在谷歌上使用Node.js和Express进行同步调用?

在谷歌上使用Node.js和Express进行同步调用?
EN

Stack Overflow用户
提问于 2018-06-07 00:47:07
回答 1查看 1.8K关注 0票数 1

我正在运行一个Node.js服务器与快速与谷歌上的行动接口。为了满足请求,我需要访问外部服务器,所以我使用了Fetch库。我似乎无法让节点服务器等待web服务调用给出适当的响应。我尝试过使用Promises和Await/Async,但是我没有正确地实现它。有没有人能帮我解决这个问题?谢谢!

代码语言:javascript
复制
let fetch = require('node-fetch');
let express = require('express');
let bodyParser = require('body-parser');
let { dialogflow, Image } = require('actions-on-google');
let app = dialogflow();
let json;

function middleware(req,res,next) {
    json = req.body;
    next();
}

app.intent('StartIntent', conv => async function() {
    const response = await communicate(json);
    console.log(response);
    // Not running synchronously
    conv.ask('Need the response from above');
});

function communicate( message ) {
    let response;
    try {
        response = fetch('https://stackoverflow.com', {
            method: 'POST',
            body:   JSON.stringify(message),
            headers: {
                'Content-Type': 'application/json'
            },
        });
        return response;
    } catch(e) {
        console.log(e);
        return null;
    }
}

express().use(bodyParser.json(), middleware, app).listen(3000);

@Prisoner是正确的- conv.ask()应该只在来自communicate()结果的json数据被返回时调用。但是,此时在Promise对象中返回的唯一内容。数据作为json对象被正确检索。

代码语言:javascript
复制
let fetch = require('node-fetch');
let express = require('express');
let bodyParser = require('body-parser');
let { dialogflow, Image } = require('actions-on-google');
let app = dialogflow();
let json;

function middleware(req,res,next) {
    json = req.body;
    next();
}

app.intent('StartIntent', conv => {
    const response = communicate(json);
    console.log("StartIntent Response:");
    console.log(response); // output: Promise { <pending> }
    // Not running synchronously :(
    console.log(response.text);
    conv.ask('Need the response from above');
});

function communicate( message ) {
    let response;
    try {
        response = fetch('https://google.com', {
            method: 'POST',
            body:   JSON.stringify(message),
            headers: {
                'Content-Type': 'application/json'
            },
        }).then(function(body) {
            return body.json();
        }).then(function(json) {
            // The data is returning successfully
            // For example: {"BTCUSD":10000}
            return json;
        }).catch(function() {
            // error handling
        });
        return response; // This is returning a pending Promise
    } catch(e) {
        console.log(e);
        return null;
    }
}

express().use(bodyParser.json(), middleware, app).listen(3006);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-07 03:47:31

fetch()返回一个Promise。您可以链接communicate()then()调用,并在正文中使用conv.ask()的响应。

下面是一个简单的示例代码片段,使用node-fetch发出API调用并使用该调用的响应。(请注意,此示例正在对JSON数据执行GET请求。)

代码语言:javascript
复制
'use strict';

const { dialogflow } = require('actions-on-google');
const functions = require('firebase-functions');
const fetch = require('node-fetch');

const app = dialogflow({debug: true});

// Default Welcome Intent
app.intent('Default Welcome Intent', (conv) => {
  return apiCall().then((response) => {
    conv.ask(`Response from above ${JSON.stringify(response)}`);
  });
});

// Makes an API call to a URL to retrieve JSON data.
function apiCall() {
  const URL = 'https://example.com/data.json';
  return fetch(URL).then((response) => response.json());
}

exports.endpoint = functions.https.onRequest(app);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50725600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档