我有一个来自这篇文章的后续问题:Chaining Requests using BlueBird/ Request-Promise
我对 promise 很陌生,所以请原谅我的天真。我成功地实现了这段代码:
var BPromise = require('bluebird');
var rp = require('request-promise');
BPromise.all([
rp(optionsForRequest1),
rp(optionsForRequest2)
])
.spread(function (responseRequest1, responseRequest2) {
// Proceed with other calls...
})
.catch(function (err) {
// Will be called if at least one request fails.
});
但在我的例子中,特定的 url 每次都不同。我想获取新的 URL 数组,为每个 URL 构造选项对象,然后是 rp()。
当我从字面上构造一个像这样的数组时 - var freshArray =[rp({Uri1 w/options}), rp({Uri2 w/options}), etc]
并将其粘贴到上面的 .all( ) - 运气不好。我认为 rp() 的实现独立于 BPromise.all 调用?
我如何将构造好的 promise 数组动态地嵌入到上面的代码中?
最佳答案
我不太确定你想做什么,但是会
BPromise.all([optionsForRequest1, optionsForRequest2].map((url) => {
const urlWithOptions = someFunction(url);
return rp(urlWithOptions);
})])
.spread(function (responseRequest1, responseRequest2) {
// Proceed with other calls...
})
.catch(function (err) {
// Will be called if at least one request fails.
});
工作?如果是这样,您甚至可以在 map 中使用 (url) => rp(someFunction(url))
缩短它
===编辑===
(x) => y
是一个 es6 简写,大部分时间都像function(x) { return y; }
(x) => { ... 返回 y;
是一个类似的速记,让你有中间变量。互联网上关于 es6 的更多信息 :) 喜欢 here
.map
是定义在数组上的函数。它将函数应用于每个元素,因此[1, 2].map((x) => x + 1)
返回[2, 3]
所以代码是这样的
var urls = [optionsForRequest1, optionsForRequest2];
var urlsWithOptions = [];
for (var k in urls) {
urlsWithOptions.push(someFunction(urls[k]));
}
BPromise.all(urlsWithOptions)
...
关于javascript - Bluebird 请求函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39300205/