最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get value from resolved jQuery.Deferred()? - Stack Overflow

programmeradmin5浏览0评论

Here is my basic situation:

function somePostThing() {
  return $post("/someUrl").done(doSomething);
}

function doSomething(data) {
  // do stuff with the data
}

var object = {};
object.deferred = somePostThing();

// A few cycles later, object.deferred may be resolved or unresolved
object.deferred.done(function () { /* ... */ });

The last line may or may not work, because done won't fire in the event that the deferred object is already resolved. I would like to be able to do something like this:

function doSomethingWithData(data) {
  // do stuff
}

var value;
if (object.deferred.isResolved()) doSomethingWithData(object.deferred.value());
else object.deferred.done(doSomethingWithData);

How do I get the value of an already resolved jQuery.Deferred()?

Here is my basic situation:

function somePostThing() {
  return $post("/someUrl").done(doSomething);
}

function doSomething(data) {
  // do stuff with the data
}

var object = {};
object.deferred = somePostThing();

// A few cycles later, object.deferred may be resolved or unresolved
object.deferred.done(function () { /* ... */ });

The last line may or may not work, because done won't fire in the event that the deferred object is already resolved. I would like to be able to do something like this:

function doSomethingWithData(data) {
  // do stuff
}

var value;
if (object.deferred.isResolved()) doSomethingWithData(object.deferred.value());
else object.deferred.done(doSomethingWithData);

How do I get the value of an already resolved jQuery.Deferred()?

Share Improve this question asked Oct 19, 2011 at 15:50 benekastahbenekastah 5,7111 gold badge36 silver badges50 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

No, that's actually exactly why the whole "Deferred" mechanism came into being. If you pass in a "done" function after the asynchronous process has been resolved, it most definitely will be executed immediately.

From the jQuery API docs:

If more functions are added by deferred.then() after the Deferred is resolved, they are called immediately with the arguments previously provided.

That's true for the ".done()" functions also.

JavaScript in a browser is single threaded. So, in the following code snippet:

object.deferred = somePostThing();

// Nothing can happen to object.deferred here

object.deferred.done(function () { /* ... */ });

nothing will happen in between the first line and the last line. "A few cycles later" doesn't mean anything in JavaScript-land. Something will only happen to object.deferred after the function that is executing returns.

发布评论

评论列表(0)

  1. 暂无评论