What is wrong with promise resolving?

前端 未结 2 1507
走了就别回头了
走了就别回头了 2020-12-12 05:51

Any ideas? Why does node say \'filename is undefined\'? Thanks. Contract, policy ans invoice functions resolve with no data, just resolve().

var dc = functio         


        
2条回答
  •  被撕碎了的回忆
    2020-12-12 06:32

    It looks like you don't care about the order, in which case you could use Promise.all. Does this work for you? It will resolve once all of the promises have been resolved, or it will reject as soon as any one of them rejects.

    function contract(data) { return new Promise(...) }
    function policy(data) { return new Promise(...) }
    function invoice(data) { return new Promise(...) }
    
    function dc(data) {
      var filename = 'Test';
      return new Promise(function(resolve, reject) {
        Promise.all([contract(data), policy(data), invoice(data)]).then(
          function (values) {
            console.log(filename);
            resolve(filename)
          },
          function (err) {
            reject(err);
          }
        );
      });
    }
    

    If you care about the order, then you do have to chain them, like you've tried to do. You're code is passing promises as an argument to then. You need to pass functions.

    function contract(data) { return new Promise(...) }
    function policy(data) { return new Promise(...) }
    function invoice(data) { return new Promise(...) }
    
    function dc(data) {
      var filename = 'Test';
      return new Promise(function(resolve, reject) {
        contract(data).then(
          function (contract_res) {
            policy(data).then(
              function (policy_res) {
                invoice(data).then(
                  function (invoice_res) {
                    console.log(filename);
                    resolve(filename);
                  },
                  function (err) { reject(err); } // invoice promise rejected
                );
              },
              function (err) { reject(err); } // policy promise rejected
            );
          },
          function (err) { reject(err); } // contract policy rejected
        );
      });
    }
    

    You may be able to simplify this with catch, but the deep nesting is a pain. Take a look at this post about flattening Promise chains.

提交回复
热议问题