2017-06-20 66 views
1

我收到来自dynamodb.scan()的承诺。如果响应包含LastEvaluatedKey,则承诺解决,那么必须再次调用dynamodb.scan()。当响应不包含LastEvaluatedKey对象时,已经扫描了表的所有记录并且查询完成。我不知道预先需要扫描的呼叫数量()。我不知道如何编码。这是我现在有:如何使用承诺与多次调用dynamodb扫描

function scan(options, startKey) { 
    var parms = { 
    TableName: options.source, 
    ProjectionExpression: "book, bid, #kee, #unt, pid, #txt", 
    FilterExpression: "contains(#txt, :v_qs)", 
    ExpressionAttributeNames: { 
     "#unt": "unit", 
     "#txt": "text", 
     "#kee": "key" 
    }, 
    ExpressionAttributeValues: { 
     ":v_qs": options.queryTransformed 
    } 
    }; 

    if (startKey) { 
    parms.ExclusiveStartKey = startKey; 
    } 

    return dynamoDb.scan(parms).promise(); 
} 

scan(options).then(function(response) { 
    if (response.LastEvaluatedKey) { 
    searchResults.push(response); 
    return scan(options, response.LastEvaluatedkey); 
    } 
    else { 
    return response 
    } 
}).then(function(response) { 
    if (response.LastEvaluatedKey) { 
    searchResults.push(response); 
    return scan(options, response.LastEvaluatedKey); 
    } 
    else { 
    return response; 
    } 
}).then(function(response) { 
    //this is crazy - bailing even if another call is needed 
    searchResults.push(response); 
    return generateSearchResponse(); 
}); 

,这显然是不能做到这一点。此代码是AWS Lambda节点功能的一部分。在此先感谢您的帮助。

回答

0

递归函数应该是你的朋友。我无法自己测试它,但是像这样的东西应该可以工作。如果您遇到任何错误,请告知我们

function scan(options, startKey) { 
    var parms = { 
    TableName: options.source, 
    ProjectionExpression: "book, bid, #kee, #unt, pid, #txt", 
    FilterExpression: "contains(#txt, :v_qs)", 
    ExpressionAttributeNames: { 
     "#unt": "unit", 
     "#txt": "text", 
     "#kee": "key" 
    }, 
    ExpressionAttributeValues: { 
     ":v_qs": options.queryTransformed 
    } 
    }; 

    if (startKey) { 
    parms.ExclusiveStartKey = startKey; 
    } 

    return dynamoDb.scan(parms).promise(); 
} 

function processResponse(options, response) { 
    return (response && response.LastEvaluatedKey) ? 
     scan(options, response.LastEvaluatedkey) 
      .then(function(next_response) { 
       return [response].concat(processResponse(next_response)); 
      }) 
     : 
     Promise.resolve(response); // replace 'Promise' by whatever Promise library you are using (when, bluebird, ...) 
} 

scan(options) 
    .then(processResponse.bind(null, options)) 
    .then(function(response_list) { 
     // response_list is an array of response 
     return generateSearchResponse(); 
    });