2015-05-15 5 views
1

Я пытаюсь переложить обещания, но второй не вызывает функцию разрешения. Что я делаю неправильно?ECMAScript 6 Цепочные обещания

 
function getCustomers(){ 

    let promise = new Promise(
    function (resolve, reject){ 

     console.log("Getting customers"); 
     // Emulate an async server call here 
     setTimeout(function(){ 
     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(
    function (resolve, reject){ 

     console.log("Getting orders"); 
     // Emulate an async server call here 
     setTimeout(function(){ 
     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"); 

Кодовые печатает "Получение заказов" от второй функции, но не печатает "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)); 

ответ

4

Вы хотите приковать обработчик успеха (для вашего 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 callback фактически не вызывается с cust, но с результатом первого then callback - и console.log возвращает undefined, с которым getOrders возникнут проблемы.

либо Вы бы

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

или проще просто

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

Спасибо, Берги. –

+0

Я думаю, что невозможно вставить «затем», который просто печатает на консоли между цепями, которые возвращают обещания. –

+0

Отлично! Мне не хватало «возврата»; в первой печати, которая разрушала цепь. Спасибо, @Bergi –

0

Вот пример кода для последовательного выполнения для Node.js с использованием ES6 ECMAScript. Может быть, кто-то считает это полезным. 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); 
    });