简体   繁体   English

如何对单个变量使用promise?

[英]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.

相关问题 如何设置对变量的Promise响应 - How do i set the response of a promise to a variable Javascript-如何将用于查询数据库的诺言将变量发送到前端? - Javascript - How do I send my variable to my frontend from the promise I use to query the database? 我如何“检查”用户是否使用承诺? - How do I “check” if user use promise? 如何在变量中存储 promise object - How do I store a promise object inside a variable 如何从 map 中的 promise 设置 JS 变量? - How do I set JS variable from promise within map? 在返回 function 的变量之前,如何等待 promise 完成? - How do I wait for a promise to finish before returning the variable of a function? 如何声明 promise 变量,以便我可以在 promise 得到解决之前在任何地方使用它 - How to declare a promise variable so that i can use it anywhere before promise gets resolved 如何根据承诺解析将承诺的结果手动输入到范围变量中? - How do I get the results of a promise into a scoped variable manually upon promise resolution? 如何在Firebase身份验证和Firebase中使用Javascript Promise链接? - How do I use Javascript Promise Chaining with Firebase Authentication and Firebase? 如何在 React 组件中使用 Promise.all 结果? - How do I use Promise.all results in a React component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM