【问题标题】:ECMAScript 6 Chaining PromisesECMAScript 6 链式 Promise
【发布时间】:2015-07-27 22:18:07
【问题描述】:

我正在尝试链接承诺,但第二个没有调用 resolve 函数。我做错了什么?

function getCustomers(){

  let promise = new Promise((resolve, reject) => {
      console.log("Getting customers");
      // Emulate an async server call here
      setTimeout(() => {
        var success = true;
        if (success) {
          resolve( "John Smith"); // got the customer
        } else {
          reject("Can't get customers");
        }
      }, 1000);

     }
  );
  return promise;
}

function getOrders(customer) {

  let promise =  new Promise((resolve, reject) => {
      console.log("Getting orders");
      // Emulate an async server call here
      setTimeout(() => {
        var success = true;
        if (success) {
          resolve("Order 123"); // got the order
        } else {
          reject("Can't get orders");
        }
      }, 1000);

     }
  );
  return promise;
}

getCustomers()
  .then((cust) => getOrders(cust))
  .catch((err) => console.log(err));

console.log("Chained getCustomers and getOrders. Waiting for results");

代码从第二个函数打印“Getting orders”,但不打印“Order 123”:

获得客户 链式 getCustomers 和 getOrders。等待结果 接单

更新。我想在控制台上的返回承诺的链式方法之间插入打印。我想这样的事情是不可能的:

getCustomers()
  .then((cust) => console.log(cust))  //Can't print between chained promises?
  .then((cust) => getOrders(cust))  
  .then((order) => console.log(order))
  .catch((err) => console.error(err));

【问题讨论】:

    标签: promise ecmascript-6 es6-promise


    【解决方案1】:

    这是一个使用 ES6 ECMAScript 顺序执行 node.js 的代码示例。也许有人觉得它有用。 http://es6-features.org/#PromiseUsage https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

    var soapClient = easysoap.createClient(params);
    
    //Sequential execution for node.js using ES6 ECMAScript
    console.log('getAllFunctions:');
    soapClient.getAllFunctions()
        .then((functionArray) => {
            return new Promise((resolve, reject) => {
                console.log(functionArray);
                console.log('getMethodParamsByName:');
                resolve();
            });
        })
        .then(() => {
            return soapClient.getMethodParamsByName('test1'); //will return promise
        })
        .then((methodParams) => {
            console.log(methodParams.request); //Console log can be outside Promise like here too
            console.log(methodParams.response);
            console.log('call');
    
            return soapClient.call({ //Return promise
                method: 'test1',
                params: {
                    myArg1: 'aa',
                    myArg2: 'bb'
    
                }
            });
        })
        .then((callResponse) => {
            console.log(callResponse);  // response data as json
            console.log('end');
        })
        .catch((err) => {
            throw new Error(err);
        });
    

    【讨论】:

      【解决方案2】:

      您想要链接成功处理程序(对于您的resolve 结果"Order 123"),而不是错误处理程序。所以使用then 而不是catch :-)

      getCustomers()
        .then(getOrders)
        .then((orders) => console.log(orders))
        .catch((err) => console.error(err));
      

      没有任何承诺被拒绝,因此您代码中的 console.log(err) 从未被调用过。

      我想在返回承诺的链式方法之间插入控制台上的打印。我想这样的事情是不可能的:

      getCustomers()
        .then((cust) => console.log(cust))  //Can't print between chained promises?
        .then((cust) => getOrders(cust))
      

      是的,这是可能的,但是您在这里拦截了一条链。所以第二个then回调实际上不是用cust调用的,而是第一个then回调的结果——而console.log返回undefinedgetOrders会出现一些问题。

      你要么做

      var customers = getCustomers();
      customers.then(console.log);
      customers.then(getOrders).then((orders) => …)
      

      或者更简单

      getCustomers()
        .then((cust) => { console.log(cust); return cust; })
        .then(getOrders)
        .then((orders) => …)
      

      【讨论】:

      • 我猜不可能在返回承诺的链式 then 之间插入仅在控制台上打印的“then”。
      • 完美!我错过了“return cust”;在第一个印刷品中,它打破了链条。谢谢你,@Bergi
      • Promise.prototype.log = function(message){ this.then(function(v){ console.log(message); return v; }) } 讨厌的人会讨厌。
      • @BenjaminGruenbaum:检测到缺少return :-) Promise.prototype.log = function(m){this.then(console.log.bind(console, m)); return this; }
      猜你喜欢
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 1970-01-01
      • 2014-03-02
      • 2015-02-12
      • 2011-10-10
      • 2015-09-08
      相关资源
      最近更新 更多