Javascript异步返回值 [英] Javascript Asynchronous Return Value

查看:78
本文介绍了Javascript异步返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我以为我理解JS范围...

Just as I thought I understood JS scope...

取此代码:

function init() {

    var page;
    var pageName = $('body').data('page');

    switch(pageName) {

        // (there are more switch cases here normally...)                   

        case 'pSearchLatest':
           require(['searchresults'], function (SearchResults) {
               page = new SearchResults().init();
               console.log(page); // <- shows the object!
           });

        default:
           break;

     }

     console.log(page); // <- undefined
     return page;

}

查看控制台日志评论。当在switch语句的范围之外声明 var page 时,为什么第二个返回 undefined

See the console log comments. Why is the second returning undefined when the var page is declared outside of the scope of the switch statement?

编辑

所以我错误地认为这是一个范围问题,但它归结为异步AMD的本质。

So I mistakenly thought this was a scope issue but it's down to the asynchronous nature of AMD.

如果没有while循环检查undefined,我如何在同一方法中返回require范围内的page值?

How can I return the value of page in the require scope in the same method without a while loop checking for undefined?

编辑2

我是这样做的:

function init(callback) {

   case 'pSearchLatest':
      require(['searchresults'], function (SearchResults) {
          page = new SearchResults().init();
          callback(page)
      });
}

在我的页面中调用包装init()方法:

and in my page that calls the wrapping init() method:

new PageController().init(function(asyncViewController) {
   App.view = asyncViewController;
});


推荐答案

您确实理解了范围。该内部函数中的代码确实分配给外部作用域中的变量。

You did understand scope correctly. The code in that inner function does indeed assign to the variable in the outer scope.

您不理解的是异步行为。 require 函数接受一个回调函数,该函数将在以后被调用 - 当请求的模块可用时。然而,它会立即返回并且控制流将导致 console.log 语句,该语句打印 undefined - 其中是页面变量当时的值

What you did not understand is asynchronous behaviour. The require function takes a callback function which will be invoked somewhen in the future - when the requested module is available. Yet, it does immediately return and control flow will lead to the console.log statement, which does print undefined - which is the value the page variable has at that time.

你应该能够识别,因为 undefined 首先记录 ,并且回调中的日志语句(带有对象)稍后执行 ,即使它在代码中出现。

You should be able to recognise that since the undefined is logged first, and the log statement in the callback (with the object) executes later, even though it comes above in the code.

这篇关于Javascript异步返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆