简体   繁体   English

JavaScript-我在做什么错?

[英]javascript - what am I doing wrong?

I would like to understand this behavior of Promise.all . 我想了解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: 然后我有一个promise.all

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); 当我运行'then'show [false,true]时:这似乎很正常,但是我不明白的是,如果我像这样更改回调函数cb({exists: exists, m: m}, err); , I receive only json, there is no more array. ,我只收到json,没有更多的数组。 I would like to receive array containing m and if the module exists or not (something like this : [{m: true/false}, {m: true/false}]). 我想接收包含m的数组,以及模块是否存在(例如:[{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. 但是,无论如何这都不是应使用promisify的方式。 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};
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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