[英]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
到控制台日志。
幾個問題:
then()
方法的第一個參數是將作為resolve()
方法運行的函數嗎?
是then()
方法還返回一個值為promise的值,並且此promise與它鏈接到其(父對象)的promise是相同的promise, 只有其resolve()
方法的值是resolve()
返回的值then()
內部的方法 ?
這是諾言嗎:
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);
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); });
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);});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.