簡體   English   中英

javascript鏈接承諾澄清

[英]javascript chaining promises clarification

我試圖弄清楚javascript中的promises概念。

我看了下面的代碼:

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()方法還返回一個值為promise的值,並且此promise與它鏈接到其(父對象)的promise是相同的promise, 只有其resolve()方法的值是resolve()返回的值then()內部的方法

  3. 這是諾言嗎:

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

等同於下面的這個承諾?

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

另外,當then()接受諾言時會發生什么情況?

像這個例子一樣?

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);
  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”的promise,而第二個代碼將返回“ bbb”而不記錄“ aaa”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM