【发布时间】: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
到控制台日志。
几个问题:
then()方法的第一个参数是作为resolve()方法运行的函数吗?then()方法还返回一个值,它是一个承诺,这个承诺与它所链接的承诺(它的父级)是同一个承诺只有它的resolve()方法的值是then()内部resolve()方法返回的值?-
这是承诺吗:
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