我需要做两个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();
}
});
});
代码可以工作,但是这种请求嵌套并不美观。有没有办法对变量做出 promise ,然后在设置该变量时触发函数?
最佳答案
您正在使用request-promise
,但仍然使用老式的回调,这就是为什么事情看起来如此困惑。
很难弄清楚您要做什么,但如果第二个请求依赖于第一个请求的信息,您可以将其放入 then
回调中并返回它为您提供的新 promise :
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
});
关于javascript - 如何对单个变量使用 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41432349/