等待回调将在FOR循环中返回值

时间:2015-12-17 07:19:02

标签: javascript typescript

我必须检测某些技术是否对我的Web浏览器有效,并且我不知道如何等待包含回调的函数在FOR循环中返回某个值。

interface IVerify {
    verify: () => boolean;
}

class A {
    verifiers: Array<IVerify>

    constructor() {
        this.verifiers = new Array<IVerify>();
    }

    public regist(x: IVerify) {
        this.verifiers.push(x);
    }

    public verifyVerifiers() {
        for (var i = 0; i < this.verifiers.length; ++i) {
            alert(this.verifiers[i].verify());
        }
    }
}

class B implements IVerify {
    verify(): boolean {
        return true;
    }
}

class C implements IVerify {
    verify(): boolean {
        var valid: boolean;
        var fs: any = (<any>window).RequestFileSystem || (<any>window).webkitRequestFileSystem;
        fs((<any>window).TEMPORARY, 1, (fs) => {
            valid = true;
        }, (err) => {
            valid = false;
        });           
        return valid;
    }
}

var a: A = new A();
var b: B = new B();
var c: C = new C();
a.regist(b);
a.regist(c);
a.verifyVerifiers();

我怎么能等到c.verify()返回true / false(现在它返回undefined)。

1 个答案:

答案 0 :(得分:1)

好的,我相信这可能对你有所帮助 - 它是纯粹的JavaScript:

var promises = [];

for (var i = 0; i < 5; i++) {
    promises.push(
    new Promise(function(resolve, reject) {
      window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;

      window.requestFileSystem(window.PERSISTENT, 1024*1024, function onInitFs() {
        resolve("Stuff worked!");
      }, function errorHandler() {  
        reject(Error("It broke"));
      });
    })
  );
}

Promise.all(promises).then(function(values) { 
  console.log(values); // [3, 1337, "foo"] 
});

https://jsfiddle.net/Lc1smhbq/1/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all