我需要做两个http请求。第二个http请求需要第一个http请求的信息。第一个请求是设置在第二个请求期间使用的变量'amount'。
这是我的代码部分。
(变量'url'和'number'存在,foo()是其他东西。)
var Promise = require('bluebird');
var request = require('request-promise');
var amount;
request({url: url, json: true }, function(error, response, body) {
if (!error && response.statusCode == 200) {
amount = body.num;
}
}).then(function(data) {
if (number == null || number > amount) {
number = Math.floor(Math.random() * amount) + 1;
}
request({
url: url,
json: true
}, function(error, response, body) {
if(!error & response.statusCode == 200) {
foo();
}
});
});
代码正在运行,但这种请求嵌套并不美观。有没有办法对变量做出承诺,然后在设置变量后触发函数?
答案 0 :(得分:2)
你正在使用request-promise
,但仍然使用过时的回调,这就是为什么事情看起来很混乱。
很难弄清楚你想要做什么,但是如果第二个请求依赖于第一个请求的信息,你将它放在then
回调中并返回它给你的新承诺:
var Promise = require('bluebird');
// I changed `request` to `rp` because `request-promise` is not `request`, that's one of its underlying libs
var rp = require('request-promise');
// Do the first request
rp({ url: url, json: true })
.then(function(data) {
// First request is done, use its data
var amount = data.num;
// You didn't show where `number` comes from, assuming you have it in scope somewhere...
if (number == null || number > amount) {
number = Math.floor(Math.random() * amount) + 1;
}
// Do the next request; you said it uses data from the first, but didn't show that
return rp({ url: url, json: true });
})
.then(function() { // Or just `.then(foo);`, depending on your needs and what `foo` does
// Second request is done, use its data or whatever
foo();
})
.catch(function(error) {
// An error occurred in one of the requests
});