我正在尝试使用javascript Promises在某些API上发出链式请求。 在第一个函数我查询数据,我得到一个ID并返回它。在第二个函数,我得到第一个函数的ID,我查询更多的数据,在第三个函数,我发送到我的API。我的代码如下。
var express = require("express");
var app = express();
var FB = require("fb");
var request = require("request");
var Promise = require("promise");
var eventData = {};
var venueId, theUrl;
app.get("/writeEvents", function(req, res) {
Promise.resolve(1)
.then(() => {
return Promise.resolve(req.query.eventID);
})
.then(value => {
FB.options({ version: "v2.10" });
FB.setAccessToken("sometoken");
FB.api("" + value + "", { fields: eventFields }, function(results) {
if (!results || results.error) {
console.log(!results ? "error occurred" : results.error);
return;
}
venueId = results.owner.id;
console.log("first: " + venueId);
//res.send(JSON.stringify(results, null, " "));
/*EVENT*/
eventData["id"] = results.id;
eventData["name"] = results.name;
});
return Promise.resolve(venueId);
})
.then(value => {
FB.options({ version: "v2.10" });
FB.setAccessToken("sometoken");
console.log("second: " + value);
FB.api("" + value + "", { fields: pageFields }, function(resPage) {
if (!resPage || resPage.error) {
console.log(!resPage ? "error occurred" : resPage.error);
return;
}
/*VENUE*/
eventData["venue"] = {};
eventData["venue"]["id"] = resPage.id;
eventData["venue"]["name"] = resPage.name;
});
return true;
})
.then(value => {
var toJson = JSON.stringify(eventData, null, " ");
var parametrus = encodeURIComponent(toJson);
theUrl = "https://example2.com?eventData=" + parametrus + "";
res.send(
JSON.stringify(eventData, null, " ") + " the url : " + theUrl
);
request(theUrl, function(error, response, body) {
console.log("error:", error); // Print the error if one occurred
console.log("statusCode:", response && response.statusCode); // Print the response status code if a response was received
console.log("body:", body); // Print the HTML for the Google homepage.
});
return Promise.resolve();
})
.catch(error => {
console.log(error);
});
});
app.listen(port);
当我在浏览器中点击example.com/writeEvents?eventID=1906888876040770
我在屏幕上打印了以下内容
{} the url : https://example2.com/writeEventsTwo?eventData=%7B%7D
在控制台
正如你所看到的......第二张照片是在第一张照片开始之前拍摄的! 知道它失败的原因吗?