Javascript 如何对单个变量使用promise?
我需要做两个http请求。第二个http请求需要来自第一个http请求的信息。第一个请求是设置变量“amount”,该变量在第二个请求期间使用 这是我的代码部分 (变量“url”和“number”是存在的,foo()是其他变量。)Javascript 如何对单个变量使用promise?,javascript,node.js,request,promise,bluebird,Javascript,Node.js,Request,Promise,Bluebird,我需要做两个http请求。第二个http请求需要来自第一个http请求的信息。第一个请求是设置变量“amount”,该变量在第二个请求期间使用 这是我的代码部分 (变量“url”和“number”是存在的,foo()是其他变量。) 代码正在运行,但对于这种嵌套的请求来说并不漂亮。有没有一种方法可以承诺一个变量,然后在设置该变量后触发一个函数?您使用的是请求承诺,但仍然使用老式的回调,这就是事情看起来如此混乱的原因 很难弄清楚您想做什么,但是如果第二个请求依赖于第一个请求的信息,您可以将其放入回调
代码正在运行,但对于这种嵌套的请求来说并不漂亮。有没有一种方法可以承诺一个变量,然后在设置该变量后触发一个函数?您使用的是
请求承诺
,但仍然使用老式的回调,这就是事情看起来如此混乱的原因
很难弄清楚您想做什么,但是如果第二个请求依赖于第一个请求的信息,您可以将其放入回调中,然后返回它给您的新承诺:
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
});
您正在使用请求承诺
,但仍然使用老式的回调,这就是事情看起来如此混乱的原因
很难弄清楚您想做什么,但是如果第二个请求依赖于第一个请求的信息,您可以将其放入回调中,然后返回它给您的新承诺:
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
});
您正在使用但仍在使用非承诺回调。为什么?number
来自哪里?您正在使用但仍然使用非承诺回调。为什么?编号从哪里来?