如何对单个变量使用 promise?

how do I use promise for a single variable?

我需要做两个 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();
            }
          });  
        });

代码可以正常工作,但这种嵌套请求并不美观。有没有办法承诺一个变量,然后在设置该变量时触发一个函数?

您正在使用 request-promise 但仍在使用老式的回调,这就是为什么事情看起来如此混乱的原因。

很难弄清楚你想做什么,但如果第二个请求依赖于第一个请求的信息,你将它放在 then 回调和 return 新的承诺中它给你:

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
    });