[英]how do I use promise for a single variable?
I need to do two http requests. 我需要执行两个http请求。 The second http request requires information from the first one.
第二个http请求需要第一个请求的信息。 The first request is to set the variable 'amount' which is used during the second request.
第一个请求是设置在第二个请求期间使用的变量“金额”。
This is a codesection of mine. 这是我的代码节。
(the variables 'url' and 'number' are existent, foo() is something else.) (变量'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();
}
});
});
the code is working but it is not beautiful with this nesting of requests. 该代码正在运行,但是这种嵌套请求的效果不佳。 Is there a way to make a promise of a variable and then trigger a function when that variable has been set ?
有没有办法对一个变量作出承诺,然后在设置该变量后触发一个函数?
You're using request-promise
but still using old-fashioned callbacks, which is why things look so cluttered. 您正在使用
request-promise
但仍在使用老式的回调,这就是为什么事情看起来如此混乱的原因。
It's hard to make out what you're trying to do, but if the second request relies on information from the first, you put it in a then
callback and return the new promise it gives you: 很难弄清您要执行的操作,但是如果第二个请求依赖于第一个请求的信息,则将其放入一个
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.