等待功能执行链完成

时间:2014-03-07 22:46:18

标签: javascript phantomjs

我遇到了一些问题,我的JS代码没有按照我希望的方式执行。我的代码:

function mrInterval(){
    interval = setInterval(function() {
       if (!loadInProgress && typeof stepz[testindexz] == "function") {
           console.log("step " + (testindexz + 1));
           stepz[testindexz]();
           testindexz++;
       }
       if (typeof stepz[testindexz] != "function") {
           console.log("Crawling completed!");
           clearInterval(interval);
       }
    }, 30);
};

function getPairs(){
    var arr;
    stepz = [
        function(){
            page.open('http://data.bter.com/api/1/pairs');
        },
        function(){
            var mycont = page.plainText;
            arr = JSON.parse(mycont);
            console.log(arr);
            return arr;
        }
    ];

    mrInterval();
};

var xx = getPairs();
console.log(xx);

我的输出不是我的预期:

undefined // came from last line of code (console.log(xx))
step 1
load started
load finished
step 2
[Data that i need ] // It came from console.log inside stepz[1] in getpairs
Crawling completed!

所以问题就我所知,当我分配给变量时,我的代码没有等待函数getpairs()的执行。为了让我的代码不再执行,直到函数内部的所有函数链(getpairs)结束,我应该做什么。

0 个答案:

没有答案
相关问题