解决承诺后如何从Promise对象获取值 [英] How to fetch value from Promise object after promise has been resolved
问题描述
请注意,这是一个人为的示例.
Please note This is a contrived example.
function longFunc(){
var deferred = $.Deferred();
setTimeout(function(){
console.log("long func completed");
deferred.resolve("hello");
}, 3000);
return deferred.promise();
}
function shortAfterLongFunc(x){
console.log('short func completed with value: ' + x);
return {
a: x
};
}
processFurther(longFunc().then(shortAfterLongFunc)); // send the array for further processing
问题
在shortAfterLongFunc
完成后,我无法弄清 如何返回任何类型的对象/函数 .我可以从shortAfterLongFunc
进行console.log,但这不是我所需要的.
在这里拨弄
I am unable to figure out how to return any kind of object/function for further downstream processing after shortAfterLongFunc
completes. I can console.log from shortAfterLongFunc
but that's not what i require here.
Fiddle Here
感谢您的光临!
更新:
好的,只是让我的问题稍微好一点...这是我正在研究的一个简单用例:
Okay just to make my question slightly better...this is a simple use case I am looking at:
$.map(['H','E','L','L', 'O'], somefunc). // for each item in array apply somefunc function
function somefunc(x){ // gets called for each value 'H', 'E' etc. in the array by $.map()
var longfunc = function(y){
var deferred = $.Deferred();
setTimeout(function(){
console.log("long func completed");
deferred.resolve(y.toLocaleLowerCase());
}, 3000);
return deferred.promise();
};
var shortAfterLongFunc = function(x){
console.log('short func completed with value: ' + x);
return x;
}
// What should I do here
return longFunc(x).then(shortAfterLongFunc); // must return lower case char to the caller of someFunc
}
somefunc()
可以说将Array的每个元素处理为小写.但是,假设此处理需要很长时间并且是异步的(请考虑setTimeout),因此保证了每个元素的同步操作...但是在使用promise时,我发现自己无法返回转换后的值
somefunc()
lets say processes each element of Array to lower case. However, assume this processing takes a long time and async (think setTimeout).. hence a promise to ensure synchronous operation for each element...but on using promise I find myself not able return the transformed value
推荐答案
只需链接另一个then
调用,因为shortAfterLongFunc
返回新的Promise,您可以进一步使用它:
Just chain another then
call, since shortAfterLongFunc
returns new promise you can further work with it:
longFunc().then(shortAfterLongFunc).then(function(data) {
console.log('all is complted', data);
});
这篇关于解决承诺后如何从Promise对象获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!