关于如何使用 Jquery.deferred 使慢速同步函数返回 promise 的快速问题。 到目前为止我所做的是:
function sayIt(ms) {
setTimeout( function() { console.log('what I say'); }, ms);
}
function doIt() {
return $.Deferred( function() { sayIt(2000); }).promise();
}
doIt().then( function() { console.log('ah'); });
sayIt(2000) 总是会执行,但“then”之后的链式函数永远不会触发。
如果我这样做:
doIt().then( console.log('ah'));
“啊”立即出现,然后 2000 毫秒后出现“我说的” - 我想要的当然是相反的 - 两秒后我得到“我说的”,然后紧接着“啊” .
任何建议表示赞赏!
最佳答案
要同步执行某些操作,但仍使用 Promise,请执行以下操作:
function slowPromise() {
var def = $.Deferred();
// do something slow and synchronous
...
// resolve the deferred with the result of the slow process
def.resolve(res);
// and return the deferred
return def.promise();
}
效果是,您仍然得到一个 Promise,但该 Promise 已得到解决,因此随后在其上注册的任何 .then()
都会立即继续。
这种模式的优点是,如果您随后用异步代码替换同步代码,该函数仍然具有相同的外部接口(interface)。
关于javascript - Jquery.deferred 的语法,使同步函数返回 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10664466/