【问题标题】:Async function pass data to async function [duplicate]异步函数将数据传递给异步函数[重复]
【发布时间】:2015-12-01 20:42:58
【问题描述】:

我有以下代码:

//calling AsyncFunction
var coords = LocationSerivice.getLocation();
var localStores;

 setTimeout(function(){

            //works
            console.log(coords);

            //calling async function again
            localStores = LocalStoresService.getLocalStores(coords[0],coords[1]);



        }, 100);

        setTimeout(function(){

                    //doesn't work
                    console.log(localStores);



               }, 100);

我想要做的是首先调用一个返回我的位置的异步函数。然后为了从该函数中获取数据,我设置了超时。收到数据后,我正在调用第二个异步函数。我再次设置超时以从我的第二个异步函数中获取数据,所以这里失败了。如果我尝试在超时块中显示带有console.log() 的数据,它会显示undefined 而console.log() 在第一个超时块​​中有效。

我也尝试过增加超时时间,但它不起作用。 有什么建议可以克服吗?

【问题讨论】:

标签: javascript angularjs asynchronous ionic


【解决方案1】:

据我了解,您的项目可能正在使用 angularjs,我在此基础上给出示例,

.factory('LocationSerivice', function ($http) {

return{

     getLocation : function () {
       return  $http.get('location_api');
     };

     getLocalStores : function(coords){
       return $http.get('your_local_store_api');
     };

  }
 });

现在调用你的 API

LocationService.getLocation().success(function(coords){
       LocationService.getLocalStores(coords).success(function(localStores){
           console.log(localStores);
       });
});

【讨论】:

    【解决方案2】:

    您可以修改您的 LocalStoresService.getLocalStores 方法以接受回调。

    function getLocalStores (arg1, arg2, cb) {
        // do stuff.
        var localStores = 'w/e';
        if (typeof cb === 'function') return cb(localStores);
    }
    

    所以你的调用方法应该是这样的:

    var coords = LocationService.getLocation();
    
    LocalStoresService.getLocalStores(coords[0], coords[1], function (localStores) {
        console.log(localStores); // 'w/e'
    });
    

    这实际上取决于您使用的技术类型,因为异步方法的“正确”实现可能因类型而异(AngularJS、NodeJS、vanilla JS 等)。

    【讨论】:

    • 问题上的标签之一是angularjs,所以我认为promise是要走的路
    • 我完全同意,Angular 是 Ionic 的核心,所以没有争议。我举了一个香草 JS 的例子,因为在我看来他处于初学者的水平。
    • 太棒了!承诺解决了我的问题:)
    猜你喜欢
    • 2020-08-03
    • 2021-12-29
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    相关资源
    最近更新 更多