请注意这是一个人为的例子。
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 但这不是我在这里需要的。
Fiddle Here
感谢您的关注!
更新:
好吧,只是为了让我的问题稍微好一点...这是我正在查看的一个简单用例:
$.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 确保每个元素的同步操作......但是在使用 promise 时我发现自己无法返回转换后的值
最佳答案
只需链接另一个 then
调用,因为 shortAfterLongFunc
返回新的 promise ,您可以进一步使用它:
longFunc().then(shortAfterLongFunc).then(function(data) {
console.log('all is complted', data);
});
演示:http://jsfiddle.net/ebt4pxxa/2/
关于javascript - promise 解决后如何从 Promise 对象中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27550394/