Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two things that you need to understand here:</p> <ol> <li><code>fetch</code> is asynchronous.</li> <li>Some <code>console.log</code>s are asynchronous.</li> </ol> <p>So this is what's happening:</p> <ol> <li>You call <code>@user.fetch()</code> and it launches an AJAX call.</li> <li>You call <code>console.log(@user)</code> and that does another bit of asynchronous work but (and this is a big but!), it takes a reference to <code>@user</code> along with it, the reference will be dereferenced when the <code>console.log</code> call does its logging.</li> <li>You call <code>console.log(@user.get('email'))</code>, this takes along what <code>@user.get('email')</code> <em>returns</em>, the <code>get</code> call will be executed immediately.</li> <li>The AJAX call from <strong>(1)</strong> returns some stuff for <code>@user</code>.</li> <li>The <code>console.log</code> calls get around to logging things in the console.</li> </ol> <p>The <code>console.log</code> from <strong>(2)</strong> carries a reference to the <code>@user</code> that <code>fetch</code> populates in <strong>(4)</strong>; by the time <strong>(4)</strong> executes, <code>@user</code> has been populated so you see a full user in the console. When you call <code>@user.get('email')</code> in <strong>(3)</strong>, the <code>fetch</code> hasn't populated <code>@user</code> yet so <code>@user.get('email')</code> is <code>undefined</code> and you're actually saying</p> <pre><code>console.log(undefined) </code></pre> <p>The arguments for the <code>console.log</code> calls will be evaluated (but the final results that are passed to <code>console.log</code> will not dereferenced!) when you call the function rather than when it finishes executing and puts things in the console.</p> <p>So you have various asynchronous things mixing together and therein lies the confusion.</p> <p>If you change your code to this:</p> <pre><code>@user = new models.User @user.fetch(success: =&gt; console.log(@user) console.log(@user.get('email')) ) </code></pre> <p>you'll get the results that you're expecting.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload