promise resolve before inner promise resolved

后端 未结 1 607
野性不改
野性不改 2020-12-28 22:43

I have a promise and I want it to resolve only when inner promise has resolved. Right now it resolves before the \"resolve\" function has been reached in the \"loadend\" cal

1条回答
  •  無奈伤痛
    2020-12-28 23:25

    When you don't return anything from then callbacks, it assumes synchronous operation and goes to resolve the result promise with the result (undefined) immediately.

    You need to return a promise from every asynchronous function, including then callbacks that you want to get chained.

    Specifically, your code should become

    var list = this.files.map(function(url, i) {
    //                   ^^^^ easier than [] + forEach + push
        return fetch(url).then(function(response) {
            return response.blob().then(function(buffer) {
                return new Promise(function(resolve) {
                    var myReader = new FileReader();
                    myReader.addEventListener('loadend', function(e) {
                        …
                        resolve('yo');
                    });
                    myReader.readAsArrayBuffer(buffer);
                }).then(function() {
                    window.console.log('smooth');
                    return 'smooth';
                });
            })
        });
    });
    

    or even better, flattened:

    var list = this.files.map(function(url, i) {
        return fetch(url).then(function(response) {
            return response.blob();
        }).then(function(buffer) {
            return new Promise(function(resolve) {
                var myReader = new FileReader();
                myReader.addEventListener('loadend', function(e) {
                    …
                    resolve('yo');
                });
                myReader.readAsArrayBuffer(buffer);
            });
        }).then(function() {
            window.console.log('smooth');
            return 'smooth';
        });
    });
    

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