ECMAScript 6链接承诺

Yak*_*ain 2 promise ecmascript-6 es6-promise

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

函数getCustomers(){

  让诺言=新的承诺(
     功能(解决,拒绝){

      console.log(“获得客户”);
        //在此处模拟异步服务器调用
      setTimeout(function(){
        var success = true;
        如果(成功){
          解析(“约翰·史密斯”);//获得客户
        }其他{
          拒绝(“无法获得客户”);
        }
      },1000);

     }
  );
  回报承诺;
}

函数getOrders(customer){

  让诺言=新的承诺(
     功能(解决,拒绝){

      console.log(“获取订单”);
        //在此处模拟异步服务器调用
      setTimeout(function(){
        var success = true;
        如果(成功){
          resolve(“ Order 123”);//得到订单
        }其他{
          拒绝(“无法获得订单”);
        }
      },1000);

     }
  );
  回报承诺;
}

getCustomers()
  .then((cust)=> getOrders(cust))
  .catch((err)=> console.log(err));
console.log(“束缚getCustomers和getOrders。等待结果”);

该代码从第二个功能打印“获取订单”,但不打印“订单123”:

让客户链接在一起的getCustomers和getOrders。等待结果获得订单

更新。我想在控制台中将打印内容插入返回承诺的链接方法之间。我猜这是不可能的:

getCustomers()
  .then((cust)=> console.log(cust))//不能在链接的promise之间打印?
  .then((cust)=> getOrders(cust))  
  .then((命令)=> console.log(命令))
  .catch((err)=> console.error(err));

Ber*_*rgi 6

您要链接成功处理程序(针对您的resolveresult "Order 123"),而不是错误处理程序。所以用then代替catch:-)

getCustomers()
  .then(getOrders)
  .then((orders) => console.log(orders))
  .catch((err) => console.error(err));
Run Code Online (Sandbox Code Playgroud)

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

我想在控制台中将打印内容插入返回承诺的链接方法之间。我猜这是不可能的:

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

是的,有可能,但是您正在此处拦截链条。因此,then实际上不是使用调用第二个回调cust,而是使用第一个then回调的结果-和console.logreturn undefined,这getOrders将带来一些问题。

你要么做

var customers = getCustomers();
customers.then(console.log);
customers.then(getOrders).then((orders) => …)
Run Code Online (Sandbox Code Playgroud)

或更简单

getCustomers()
  .then((cust) => { console.log(cust); return cust; })
  .then(getOrders)
  .then((orders) => …)
Run Code Online (Sandbox Code Playgroud)