简体   繁体   中英

javascript - what am I doing wrong?

I would like to understand this behavior of Promise.all .

  var checkIfModuleExists = promisify(
    function (m, cb){
      var doc = {
        index: 'app1',
        type: 'm1',
        id: m.id,
        body: { }
      };
      client.exists(doc ,
        function (err, exists) {
          cb(err, exists);
        });
    });

and then I have a promise.all like this:

var module = [{id: 'aa'}, {id: 'bb'}];
Promise.all( modules.map(function(module){
      return checkIfModuleExists(module);
    })).then(function(data){
      console.log(data);
    }).catch(function(err){
      console.log(err);
    });

When I run this 'then' show [false, true]: this seems normal, but what I don't understand is that if I change my callback function like this cb({exists: exists, m: m}, err); , I receive only json, there is no more array. I would like to receive array containing m and if the module exists or not (something like this : [{m: true/false}, {m: true/false}]). Can you please explain this behavior and how to can get an array containing every module an his status ? Thanks

As mentioned in the comments, you confused the error and result parameters. What happens is that the first promise will reject, causing your error handler to be executed with the object you expected.

However, this isn't how you should use promisify anyway. Rather do

var clientExists = promisify(client.exists, {context:client});
function checkIfModuleExists(m) {
    return clientExists({
        index: 'app1',
        type: 'm1',
        id: m.id,
        body: { }
    }).then(function(exists) {
        return {exists: exists, m: m};
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM