logo
down
shadow

Trouble with promises bluebird in node.js


Trouble with promises bluebird in node.js

By : user50015
Date : November 22 2020, 01:01 AM
To fix the issue you can do Promises represent a value + time. Promises have state, they start as pending and can settle to:
fulfilled meaning that the computation completed successfully. rejected meaning that the computation failed.
code :
var network = {
  getReportsFromCity: function(cityId) {
    return models.index.reports.findAll({ // NOTE THE RETURN
      where: { id: cityId },
      attributes: ['id', 'latitude', 'longitude']
    }).then(function(reports) {
      console.log('[NETWORK-OFR] Get reports from %s', cityId);
      return reports;
    }).catch(function(err){
      console.log('Error getting reports from %s', cityId);
      console.log(err);
    });
  }
}
network.getReportsFromCity(538).then(function(data){
    console.log("Data", data);
});


Share : facebook icon twitter icon
Understanding Promises (using Bluebird and Node)

Understanding Promises (using Bluebird and Node)


By : RAJAN PRADHAN
Date : March 29 2020, 07:55 AM
This might help you
.then(dbFinancials.addStatement("XYZ", "type", moment.utc([2014, 0, 31]), 3, "none"))
code :
clearStatements()
.then(function(){
    return dbFinancials.addStatement("XYZ", "type", moment.utc([2014, 0, 31]), 3, "none")
})
.then(dbFinancials.addStatement.bind(dbFinancials, "XYZ", "type", moment.utc(), 4, "none"))
.then(function(){
    return dataCollection.isCrawlDue("XYZ");
})
.then(function (isDue) {
    assert.isTrue(isDue, "No need for a crawl detected.");
    done();
});
Using Bluebird Promises in Node.JS

Using Bluebird Promises in Node.JS


By : tanaka
Date : March 29 2020, 07:55 AM
seems to work fine If you want to capture each error separately, then you can put an error handler immediately after each operation so you can directly capture that particular error.
Then, to propagate the error, you can rethrow the error value.
code :
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));
var logger = require("./logger.js")
var projectJSON = require("../project.json");

var harPath = projectJSON.project.harfile.location;
var harFileNames = projectJSON.project.transactions.transactionsName;
var harFilePath;
var harFiles = {};
var writeFilePath = "../temp/"


harFileNames.forEach(function(harFileName){
    harFilePath = harPath + "/" + harFileName + ".har";

    fs.readFileAsync(harFilePath, "utf-8")
        .then(function(data){
            harFiles[JSON.parse(data).log.pages[0].id] = JSON.parse(data);
            return data;
        }).catch(err) {
            logger.error("error", "Error reading har files from location!");
            throw err;      // propagate error
        }).then(function(data){
            return fs.writeFile(writeFilePath + harFileName + ".json", data).catch(function(err) {
                logger.error("error", "Error writing to harFile!");
                throw err;   // propagate error
            });
        }).then(function(){
            console.log("data written successfully: ");
        }).catch(function(err){
            // either one of the errors
        });

});
function someFunc() {

    var harPath = projectJSON.project.harfile.location;
    var harFileNames = projectJSON.project.transactions.transactionsName;
    var harFilePath;
    var harFiles = {};
    var writeFilePath = "../temp/"

    return Promise.map(harFileNames, function(harFileName) {
        harFilePath = harPath + "/" + harFileName + ".har";

        return fs.readFileAsync(harFilePath, "utf-8")
            .then(function(data){
                harFiles[JSON.parse(data).log.pages[0].id] = JSON.parse(data);
                return data;
            }, function(err) {
                logger.error("error", "Error reading har files from location!");
                throw err;      // propagate error
            }).then(function(data){
                return fs.writeFile(writeFilePath + harFileName + ".json", data).catch(function(err) {
                    logger.error("error", "Error writing to harFile!");
                    throw err;   // propagate error
                });
            }).then(function(){
                console.log("data written successfully: ");
            }).catch(function(err){
                // either one of the errors
            });

    }).then(function() {
        // all results are in harFiles array here
        return harFiles;
    });
}

someFunc().then(function(hFiles) {
    // hFiles should be your files object
});
Node.js bulk download and Bluebird promises

Node.js bulk download and Bluebird promises


By : vkudyushev
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further From what I can understand, you're trying to download multiple images with promise. Actually you don't need to promisify fs. You should use request module for easier downloading.
Here's a shortest working example I can come up with
code :
var Promise = require('bluebird');
var path = require('path');
var fs = require('fs');
var request = require('request');

var images = [{
    url: 'http://bluebirdjs.com/img/logo.png',
    file_name: 'bluebird.png'
}, {
    url: 'http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png',
    file_name: 'ubuntu.png'
}, {
    url: 'https://www.raspberrypi.org/wp-content/uploads/2012/03/raspberry-pi-logo.png',
    file_name: 'raspberry-pi.png'
}];

// To Download Serially
Promise.each(images, image => new Promise((resolve, reject) => {
    console.log('Downloading Image: ' + image.file_name);
    request(image.url).on('error', reject).pipe(fs.createWriteStream(path.join(__dirname, image.file_name))).on('finish', () => {
        console.log('Downloaded Image: ' + image.file_name);
        resolve();
    });
})).then(() => {
    console.log('All Image Downloaded!');
}).catch(err => {
    console.error('Failed: ' + err.message);
});

// To Download in Parallel (with 2 maximum concurrent jobs)
Promise.map(images, image => new Promise((resolve, reject) => {
    console.log('Downloading Image: ' + image.file_name);
    request(image.url).on('error', reject).pipe(fs.createWriteStream(path.join(__dirname, image.file_name))).on('finish', () => {
        console.log('Downloaded Image: ' + image.file_name);
        resolve();
    });
}), {
    concurrency: 2
}).then(() => {
    console.log('All Image Downloaded!');
}).catch(err => {
    console.error('Failed: ' + err.message);
});
bluebird node promises, cant resolve value

bluebird node promises, cant resolve value


By : Kimberley Jane
Date : March 29 2020, 07:55 AM
will help you You appear to be chaining the .then in your routes file off of the wrong method, if you are expecting google.getUser() to return the value you want to store in user you should chain the .then on the end of that function call.
code :
router.get('/auth/google/callback', (req, res) => {

    google.getToken(req.query.code).then( () => { 

        google.getUser().then(user => {
            console.log(user); //undefined - response is NOT defined here
        }); //End getUser().then(..)

    }); //End getToken.then(..)

}); //End router.get(..)
Trouble with js promises (bluebird)

Trouble with js promises (bluebird)


By : Hailegnaw Gizaw
Date : March 29 2020, 07:55 AM
it should still fix some issue The then callback of getMergeFieldsPromise is not returning anything, so once getMergeFieldsPromise is resolved, it does not await the addMergeField promises, but instead resolves immediately (with undefined as promised value).
To solve this, make allProductIDPromises a local variable inside the then callback and call Promise.all on it, and return it there:
code :
var updateMergeFields = getMergeFieldsPromise.then( 
    function( mergeFieldList ) {
        // **** make the array of promises local to this function
        var allProductIDPromises = [];
        // resolved ids keeps track of ids that have already been added
        var resolvedIDS = {}
        //holds result of find to look for product ids
        var foundMCMatch
        // holds productIDS[i]
        var product
        //console.log("merge field list" + JSON.stringify(mergeFieldList))

        for(var i = 0; i < productIDS.length; i++) {
            console.log("checking if product id " + productIDS[i] + "exists")
            product = productIDS[i]
            // tries to find a match to see if fields are already in mailchimp
            foundMCMATCH = mergeFieldList.find(x => x.name == product)

            if(foundMCMATCH) {
                console.log("foundMCMATCH" + JSON.stringify(foundMCMATCH))

                //updates product dict with matching tag/name from mailchimp
                productDict[i] = {
                    tag : foundMCMATCH.tag, 
                    name : foundMCMATCH.name
                }
                //console.log("PRODUCT DICT " + JSON.stringify(productDict))
            }

            //if field isn't on mailchimp
            else if (!resolvedIDS[product])
            {
                resolvedIDS[product] = true

                // adds product id as merge field becasue it doesn't exist
                allProductIDPromises.push(
                    addMergeField(product,i)
                )
            }
        }
        // **** call Promise.all here, and return it
        return Promise.all(allProductIDPromises);
    }
)
allProductIDPromises.push( ... )
updateMergeFields.then(function(addedMergeFields) { 
    // ... all is ready now.
}
Related Posts Related Posts :
  • RangeError: Maximum call stack size exceeded with array.slice
  • node rest client get with local variable
  • If condition not executes while mouse move fastly
  • Count the number of displayed elements in a HTML list
  • Locate JavaScript source code in Emacs
  • Clean, Modular Code vs MV* Frameworks
  • infinite scroll without loading image
  • Backbone: reverse collection order with comparator
  • What do printers ignore?
  • jQuery UI .tabs() Contentless tab?
  • Execute Javascript alert() after page (visually) loaded
  • JavaScript - duplicating array doesn't work
  • Excessive clickable area below image
  • JavaScript Regex: Replace |b| with <b>
  • Unexpected value change in 2D array in JavaScript
  • Function doesnt see parameter as a array of objects
  • jQuery fetch keypress event on chrome and IE
  • How to enable jquery validate localization?
  • Cassandra map collection returned by node.js Helenus looks odd
  • angular ng-repeat with multiple filter options
  • Selecting Children without ID or Class names
  • How to uncheck a group of checkboxes when another checkbox is checked
  • Is hiding content by Javascript or jQuery Worth trying
  • Load XUL resource using javascript
  • XML to HTML text area from server file system
  • set focus() on textbox on form onload
  • es lint '' is assigned a value but never used' eventhough i have used it
  • Can "name" attribute be used for custom VueJS components
  • Get innerHTML of content when it is clicked
  • HTTPS causes CSS animations to not load? Very confused
  • How to hide other div apart from touched div to the band
  • Is global variable assignment atomic on NodeJS?
  • Datepicker onchangemonthyear beforeshowday
  • trying to render html files using jade but it still adresses it as a jade
  • Google Analytics - Understanding and Dissecting the Snippet: What is | | [ ];
  • Replacing "[aA09.b]." to "[aA09.b]\n" in in JavaScript
  • Why wrap a function definition in an immediate function?
  • Enable / disable jQuery script on switching to different tab in a HTML page
  • how can find return variable value outside anonymous function in node js mysql query function
  • Converting 1 to 0001 in javascript array
  • svg viewbox should not resize the text fontSize?
  • store newline character with string in a variable
  • MP4 videos in Flowplayer does not play in Windows 7 Chrome
  • jquery focusin event not firing
  • How to debug Vue application with google chrome
  • html 5 web app cache download complete javascript alert?
  • Ember.js setupController fired only once
  • How to validate a currency input
  • How to convert my Array of data to key & value pair
  • Statistics circles in CSS
  • So I wanted to make a trig solver in javascript?
  • Showing HighCharts series name on x-axis and in legend
  • In Rails, how can we pass parameters in script?
  • Build Fails: `npm rebuild node-sass --force`
  • Angular Datepicker change dateformat
  • Trying to extract data from between two sets of characters
  • Configuring Jest in WebStorm
  • Uncaught Error: Syntax error, unrecognized expression: tr.ec_portfolio_title,
  • JQuery fading in fading out continuously
  • Unexpected end of input (Line 1) and Undefined Function?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org