我正在运行一个Node.js服务器与快速与谷歌上的行动接口。为了满足请求,我需要访问外部服务器,所以我使用了Fetch库。我似乎无法让节点服务器等待web服务调用给出适当的响应。我尝试过使用Promises和Await/Async,但是我没有正确地实现它。有没有人能帮我解决这个问题?谢谢!
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对象被正确检索。
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);
发布于 2018-06-07 03:47:31
fetch()
返回一个Promise。您可以链接communicate()
的then()
调用,并在正文中使用conv.ask()
的响应。
下面是一个简单的示例代码片段,使用node-fetch发出API调用并使用该调用的响应。(请注意,此示例正在对JSON数据执行GET请求。)
'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);
https://stackoverflow.com/questions/50725600
复制相似问题