Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bluebird.js then function not firing

New to NodeJS, getting my head around promises. In this simple example below, I don't understand why the then function does not fire. The data variable is successfully set, but doesn't continue after this point.

What am I doing wrong?

var AWS = require('aws-sdk');
var Promise = require('bluebird');

var docClient = new AWS.DynamoDB.DocumentClient();
Promise.promisifyAll(Object.getPrototypeOf(docClient));

var tableQuery = {
    TableName : "Info",
    KeyConditionExpression: "#rt = :rt",
    ExpressionAttributeNames: { "#rt": "Type" },
    ExpressionAttributeValues: { ":rt": "Owner" }
}

docClient.queryAsync(tableQuery, function (err, data) {
    return data;
}).then(function(data) {
    //doesn't get here...
    return data.Items;
}).done(function (item) {
    console.log("Done." + item);
});
like image 801
Mike Avatar asked Jan 27 '26 20:01

Mike


1 Answers

.done in bluebird is to terminate a chain, do not attempt to pass anything to it. In fact - it's probably a good idea to not use it at all except in special circumstance.

Promise fulfillment then handlers do not deal with errors - .catch does where you can find the error. methods is to not conflate errors with values - so your functions that take data should take a data parameter in the then handlers rather than (err, data):

const AWS = require('aws-sdk'); // prefer const in node
const Promise = require('bluebird');

const docClient = new AWS.DynamoDB.DocumentClient();
Promise.promisifyAll(Object.getPrototypeOf(docClient));

var tableQuery = {
    TableName : "Info",
    KeyConditionExpression: "#rt = :rt",
    ExpressionAttributeNames: { "#rt": "Type" },
    ExpressionAttributeValues: { ":rt": "Owner" }
}

docClient.queryAsync(tableQuery).then(data => data.Items).then(items => {
    console.log("Done." + items);
});

Your code failed because it confused bluebird - it made it pass an additional parameter after the callback (which you were manually passing). That effectively made the promise pending forever.

like image 196
Benjamin Gruenbaum Avatar answered Jan 30 '26 08:01

Benjamin Gruenbaum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!