【问题标题】:javascript chaining promises clarificationjavascript 链接承诺澄清
【发布时间】:2016-11-09 18:13:13
【问题描述】:

我正在尝试在 javascript 中理解 Promise 的概念。

我看过这段代码:

new Promise(function(res,rej) {
    res("aaa");
})
.then(function(result) {
    console.log(result);
    return "bbb";
})
.then(function(result) {
    console.log(result);
    return "ccc";
})
.then(function(result) {
    console.log(result);
});

打印出来:

 aaa

 bbb

 ccc 

到控制台日志。

几个问题:

  1. then() 方法的第一个参数是作为resolve() 方法运行的函数吗?

  2. then() 方法还返回一个值,它是一个承诺,这个承诺与它所链接的承诺(它的父级)是同一个承诺只有它的 resolve() 方法的值是then()内部resolve()方法返回的值?

  3. 这是承诺吗:

    var myPromise = new Promise(function(res,rej) {
        res("aaa");
    })
    .then(function(result) {
        console.log(result);
        return "bbb";
    })
    

下面这个promise的等价物吗?

var myPromise = new Promise(function(res,rej) {
    res("bbb");
})

另外,当then()接受一个promise时会发生什么?

喜欢这个例子吗?

var firstMethod = function() {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         console.log('first method completed');
         resolve({data: '123'});
      }, 2000);
   });
   return promise;
};


var secondMethod = function(someStuff) {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         console.log('second method completed');
         resolve({newData: someStuff.data + ' some more data'});
      }, 2000);
   });
   return promise;
};

var thirdMethod = function(someStuff) {
   var promise = new Promise(function(resolve, reject){
      setTimeout(function() {
         console.log('third method completed');
         resolve({result: someStuff.newData});
      }, 3000);
   });
   return promise;
};

firstMethod()
   .then(secondMethod)
   .then(thirdMethod);

【问题讨论】:

  • A Promise 代表未来值。 then 使您能够将普通函数应用于包装在Promise 中的这个“未来值”。这些普通函数需要一个值(由 Promise 提供)并返回一个转换后的值,该值再次包装在一个新的 Promise 中。这是通常的情况。
  • 这里的问题太多了。你需要一次问一个问题

标签: javascript promise angular-promise q


【解决方案1】:
  1. then 方法的第一个参数是解析函数,第二个参数是拒绝函数。

var resolvedPromise = new Promise(function(res,rej){ res({data: 7}) });
var rejectedPromise = new Promise(function(res,rej){ rej('error!!!!') });
resolvedPromise.then(function(res){ console.log('resolved:' + JSON.stringify(res)); }, function (err){ console.log('rejected:' + err); });
rejectedPromise.then(function(res){ console.log('resolved:' + JSON.stringify(res)); }, function (err){ console.log('rejected:' + err); });
  1. then 方法根据前一个 Promise 的返回类型返回一个 Promise。

var promise = new Promise(function(res,rej){ res({data: 7}) });
promise.
then(function(res){ console.log(res); return res.data; }).
then(function(res){ console.log(res); return res + 1; }).
then(function(res){ console.log(res);});
  1. 没有。第一个代码将记录“aaa”并返回带有“bbb”的承诺,而第二个代码将返回“bbb”而不记录“aaa”;

【讨论】:

  • 当 then() 得到一个 promise 作为参数时发生了什么?
猜你喜欢
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-28
相关资源
最近更新 更多