How to use promise bluebird in nested for loop?

一个人想着一个人 提交于 2020-01-26 02:04:09

问题


I need to use bluebird in my code and I have no idea how to use it. My code contains nested loops. When the user logs in, my code will run. It will begin to look for any files under the user, and if there are files then, it will loop through to get the name of the files, since the name is stored in a dictionary. Once it got the name, it will store the name in an array. Once all the names are stored, it will be passed along in res.render().

Here is my code:

  router.post('/login', function(req, res){
  var username = req.body.username;
  var password = req.body.password;
  Parse.User.logIn(username, password, {
    success: function(user){
      var Files = Parse.Object.extend("File");
      var object = [];
      var query = new Parse.Query(Files);
      query.equalTo("user", Parse.User.current());
      var temp;
      query.find({
        success:function(results){
          for(var i=0; i< results.length; i++){
            var file = results[i].toJSON();
            for(var k in file){
              if (k ==="javaFile"){
                for(var t in file[k]){
                 if (t === "name"){
                  temp = file[k][t];
                  var getname = temp.split("-").pop();
                  object[i] = getname;
                }
              }
            }
          }
        }
      }
    });
      console.log(object);
      res.render('filename', {title: 'File Name', FIles: object});
      console.log(object);
    },
    error: function(user, error) {
      console.log("Invalid username/password");
      res.render('logins');
    }
  })
});

EDIT:The code doesn't work, because on the first and second console.log(object), I get an empty array. I am suppose to get one item in that array, because I have one file saved


回答1:


JavaScript code is all parsed from top to bottom, but it doesn't necessarily execute in that order with asynchronous code. The problem is that you have the log statements inside of the success callback of your login function, but it's NOT inside of the query's success callback.

You have a few options:

  1. Move the console.log statements inside of the inner success callback so that while they may be parsed at load time, they do not execute until both callbacks have been invoked.
  2. Promisify functions that traditionally rely on and invoke callback functions, and hang then handlers off of the returned value to chain the promises together.

The first option is not using promises at all, but relying solely on callbacks. To flatten your code you will want to promisify the functions and then chain them.

I'm not familiar with the syntax you're using there with the success and error callbacks, nor am I familiar with Parse. Typically you would do something like:

query.find(someArgsHere, function(success, err) { 
});

But then you would have to nest another callback inside of that, and another callback inside of that. To "flatten" the pyramid, we make the function return a promise instead, and then we can chain the promises. Assuming that Parse.User.logIn is a callback-style function (as is Parse.Query.find), you might do something like:

var Promise = require('bluebird');
var login = Promise.promisify(Parse.User.logIn);
var find = Promise.promisify(Parse.Query.find);
var outerOutput = [];

return login(yourArgsHere)
  .then(function(user) {
    return find(user.someValue);
  })
  .then(function(results) {
    var innerOutput = [];
    // do something with innerOutput or outerOutput and render it
  });

This should look familiar to synchronous code that you might be used to, except instead of saving the returned value into a variable and then passing that variable to your next function call, you use "then" handlers to chain the promises together. You could either create the entire output variable inside of the second then handler, or you can declare the variable output prior to even starting this promise chain, and then it will be in scope for all of those functions. I have shown you both options above, but obviously you don't need to define both of those variables and assign them values. Just pick the option that suits your needs.

You can also use Bluebird's promisifyAll() function to wrap an entire library with equivalent promise-returning functions. They will all have the same name of the functions in the library suffixed with Async. So assuming the Parse library contains callback-style functions named someFunctionName() and someOtherFunc() you could do this:

var Parse = Promise.promisifyAll(require("Parse"));
var promiseyFunction = function() {
  return Parse.someFunctionNameAsync()
    .then(function(result) {
      return Parse.someOtherFuncAsync(result.someProperty);
    })
    .then(function(otherFuncResult) {
      var something;
      // do stuff to assign a value to something
      return something;
    });
}



回答2:


I have a few pointers. ... Btw tho, are you trying to use Parse's Promises?

You can get rid of those inner nested loops and a few other changes:

Use some syntax like this to be more elegant:

/// You could use a map function like this to get the files into an array of just thier names
var fileNames = matchedFiles.map(function _getJavaFile(item) {
    return item && item.javaFile && item.javaFile.name // NOT NULL
      && item.javaFile.name.split('-')[0]; // RETURN first part of name
});


// Example to filter/retrieve only valid file objs (with dashes in name)
var matchedFiles = results.filter(function _hasJavaFile(item) {
    return item && item.javaFile && item.javaFile.name // NOT NULL
         && item.javaFile.name.indexOf('-') > -1; // and has a dash
});

And here is an example on using Parse's native promises (add code above to line 4/5 below, note the 'then()' function, that's effectively now your 'callback' handler):

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.select("score", "playerName");
query.find().then(function(results) {
  // each of results will only have the selected fields available.
});


来源:https://stackoverflow.com/questions/30335542/how-to-use-promise-bluebird-in-nested-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!