在电子中使用request-promise链接HTTP请求
UPDATE
好,所以我解决了。 当使用highland.js时,我需要一个.done()来完成stream。
var requests = []; _(fs.createReadStream("small.txt", { encoding: 'utf8' })) .splitBy('-----BEGIN-----\n') .splitBy('\n-----END-----\n') .filter(chunk => chunk !== '') .each(function (x) { requests.push(function (next) { Helpers.Authenticate() .then(function (response1) { return Helpers.Retrieve(); }) .then(function (response2) { return Helpers.Retrieve(); }) .then(function () { next(); }); }); })}).done(function () { async.waterfall(requests); });
request
数组现在正在工作。
我有一些使用电子和链接承诺的问题。 下面是我在主stream程中运行的代码。
var request = require('request-promise'); request.post(tppAuthenticate) .then(function (responseFromFirstPost) { var newoptions = tppRetrieveCertificate(responseFromFirstPost.APIKey) return request.post(newoptions) // The return is important }) .then(function (responseFromSecondPost) { console.log(responseFromSecondPost) })
整个代码块通过遍历文件的每一行来调用它的数千次。 第一个请求被连续触发,但是这似乎明显地阻止/扼制了第二个只被周期性地调用的请求。
我希望整个街区能按顺序被调用,但这似乎并没有发生。
下面是我的完整的代码块,包括迭代:
const _ = require('highland'); const request = require('request-promise'); fs.createReadStream(files[0], { encoding: 'utf8' })) .splitBy('-----BEGIN -----\n') .splitBy('\n-----END -----\n') .filter(chunk => chunk !== '') // .each(_.log); .each(function (x) { request.post(tppHelpers.Authenticate) .then(function (responseFromFirstPost) { const newoptions = tppHelpers.tppRetrieveCertificate(responseFromFirstPost.APIKey) console.log(newoptions) return request.post(newoptions) // The return is important }) .then(function (responseFromSecondPost) { console.log(responseFromSecondPost) event.sender.send('selected-directory', responseFromSecondPost) }) });
如果你不想一次性发出每一个请求,这似乎是阅读你所做的评论的情况,那么就不要同时运行所有的东西:
.each(function (x) { // ... });
您可以改为在运行fs.createReadStream
之前创build一个空数组:
var requests = [];
并在您的each
callback中创build函数添加到您的数组:
.each(function (x) { requests.push(function (next) { // ... next(); }); });
然后你可以运行它与:
async.series(requests);
使用async
模块。
只要确保在适当的时候调用next()
,例如在给定的承诺链的最后一个.then()
callback中。
另一种方法是使用async.queue
:
var queue = async.queue(function(x, callback) { // callback(); }, 1);
(在这里确保callback()
被调用,而不是1,最后你可以用一些其他的号码来并行地完成一定数量的请求。)
然后在你的each
callback中:
.each(function (x) { queue.push(x); });
有关更多信息,请参阅async.queue文档。 (感谢robertklep在评论中提及async.queue()
。)
顺便说一句:你甚至在你的迭代中使用x
,或者你只是为你的input的每一行做了一堆相同的请求?
例
从评论中回答你的问题,这里是构build函数数组的一种方法。
如果这是你的原始代码:
yourStream.each(function (x) { doRequest1() .then(function (response1) { return doRequest2(); }) .then(function (response2) { return doRequest3(); }); });
那么你可以用类似这样的函数来构造这些函数:
var requests = []; yourStream.each(function (x) { requests.push(function (next) { doRequest1() .then(function (response1) { return doRequest2(); }) .then(function (response2) { return doRequest3(); }) .then(function () { next(); }); }); });
你可以运行它们:
async.series(requests);
希望能帮助到你。