Unable to call functions with Require.js

前端 未结 2 1762
执念已碎
执念已碎 2021-01-26 09:35

i try to write an module for my node.js server with require.js that just returns the object i want to get from an url. But somehow i can\'t return the values i get with my metho

相关标签:
2条回答
  • 2021-01-26 10:04

    You can't have a function that makes an async call just return something (unless it's a promise).

    You need to have your function take a callback parameter:

    function foo(callback) {
      doSomethingAsync(function(data) {
        // fire callback, which is a function that takes an argument 'data'
        callback(data)
      });
    }
    

    Then you can use it like this:

    foo(function(data) {
      doStuffWith(data);
    });
    
    0 讨论(0)
  • 2021-01-26 10:24

    The reason why you get what you get is that http.get(...) only initiates a network operation. At some indefinite point in the future the callbacks you gave to it will be executed. However, http.get(...) returns right away, before its callbacks are run. (Hence, it is an asynchronous operation). So by the time you hit your return statement the network operation is not complete yet and you return the initial value you gave to your response variable. Eventually, the network operation completes, your success callback is called and then you update response to the value you really wanted.

    As others have said, you need to use callbacks or promises. Or rethink your design.

    0 讨论(0)
提交回复
热议问题