如何在JavaScript promise字符串中的.then函数中调用带有参数的函数? [英] How do you call a function with parameters in a .then function in a JavaScript promise string?

查看:518
本文介绍了如何在JavaScript promise字符串中的.then函数中调用带有参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将用node.js编写的AWS lambda函数转换为使用promise而不是回调.我用处理程序代码将所有函数包装在处理程序中.我正在尝试突破简单的功能,以便在处理程序代码中尽可能地简化承诺链.

I am converting my AWS lambda functions, written in node.js, to use promises instead of callbacks. I'm wrapping all of my functions in the handler with the handler code. I'm trying to break out simple functions so I can have as flat a promise chain as possible in the handler code.

我被困在一个.then()函数返回一个需要传递给我的函数之一的值的地方,该函数已被确定,并带有其他参数.我搜索了高&低,但找不到执行此操作的语法示例.我什至不确定自己在做什么完全正确.我发现的所有文章都解释了简单的承诺链,这些承诺链仅通过.then()方法返回值.没有人会将它传递给另一个承诺的函数.

I'm stuck at one point where I have a .then() that returns a value that I need to pass to one of my functions, which has been promisified, along with other parameters. I have searched high & low but can't find an example of the syntax to do this. I'm not even sure what I'm doing is the right thing at all. All of the articles I've found explain simple promise chains that only return a value through the .then() method. None that then pass it into another promisified function.

这是我到目前为止所拥有的:

Here's what I have so far:

var bbPromise = require("./node_modules/bluebird");
var AWS = require("./node_modules/aws-promised");
var rp = require("./node_modules/request-promise");
var moment = require('./node_modules/moment.js');
var dynamodb = new AWS.dynamoDb();

exports.handler = function(event, context) { 
    "use-strict"; 

    // This gets a token that will be used as a parameter for a request
    function getToken(params){
        return rp.post({
            url: "https://api.something.com/oauth2/token",
            followRedirects: true,
            form: params,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).then(function(body){
            return JSON.parse(body).access_token;
        }).catch(function(error){
            console.log("could not get token: "+error);
        });
    }

    function getData(userId, db, token){ 
        var qParams = {
            // params that will get one record 
        };
        return dynamodb.queryPromised(qParams)
        .then(function (data){
            var start_date = // did some date manipulation on data to get this value
            // Request records, passing the token in the header
            var url = "https://api.something.com/data/?db="+db+"&start_date="+start_date;
            var headers = {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Authorization':'Bearer '+token
            };
            tokenParams = {all the parameters};
            rp.get({
                url:url, 
                qs:tokenParams, 
                headers:headers, 
                followRedirect: true
            }).then(function(body){
                return body;
            }).catch(function(error){
                console.log("could not get data: "+error);
            });
        }).catch(function(error){
            console.log("Final Catch - getData failed: "+error);
        });
    }

    // THIS IS WHERE THE HANDLER CODE STARTS

    // Get an array of all userIds then get their data
    dynamodb.scanPromised({
        // params that will get the user Ids
    }).then(function(users){
        for(var i=0; i<users.length; i++){
            userId = // the value from the user record;        
            // Request a token
            var tokenParams = {an object of params};
            getToken(tokenParams)
            .then(function(token){
            ///////////// THIS IS WHERE I NEED HELP /////////////////
            /* Is there a way to pass getData the token within the .then() so I don't have a nested promise? */
                getData(userId, users[i].dbName, token)

            //////////////////////////////////////////////////////////
            }).catch(function (e){
                console.log("caught an error");
            });
        }
    }).catch(function (e){
        console.log("caught an error");
    });
};

推荐答案

您可以使用Promise.all().then()Function.prototype.bind()return rp.get()来自getData()

You can use Promise.all(), .then(), Function.prototype.bind(); return rp.get() from getData()

 return Promise.all(users.map(function(user) {
   userId = // the value from the user record;        
     // Request a token
     var tokenParams = {
       an object of params
     };
   return getToken(tokenParams)
     .then(getData.bind(null, userId, user.dbName))
     .catch(function(e) {
       console.log("caught an error");
       throw e
     });
 }))

这篇关于如何在JavaScript promise字符串中的.then函数中调用带有参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆