簡體   English   中英

如何在JavaScript保證字符串中使用.then函數中的參數調用函數?

[英]How do you call a function with parameters in a .then function in a JavaScript promise string?

我正在轉換用node.js編寫的AWS lambda函數來使用promises而不是回調。 我用處理程序代碼將所有函數包裝在處理程序中。 我試圖打破簡單的函數,這樣我就可以在處理程序代碼中盡可能地保持一個承諾鏈。

我陷入了一個點,我有一個.then(),它返回一個值,我需要傳遞給我的一個函數,它已經被保證,以及其他參數。 我搜索過高和低但無法找到執行此操作的語法示例。 我甚至不確定我在做什么是正確的事情。 我發現的所有文章都解釋了簡單的promise鏈,它只通過.then()方法返回一個值。 沒有,然后將其傳遞到另一個promisified函數。

這是我到目前為止所擁有的:

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() ; getData() return rp.get() 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
     });
 }))

使用promise時,您的代碼看起來應該更像這樣。

when.try(() => {
    return api.some_api_call
})
.then((results) => {
    const whatIAmLookingFor = {
        data: results.data
    };

    someFunction(whatIAmLookingFor);
})
.then(() => {
    return api.some_other_api_call
})
.then((results) => {
    const whatIAmLookingFor = {
        data: results.data
    };

    someOtherFunction(whatIAmLookingFor); 
.catch(() => {
    console.log('oh no!');
})
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM