9

我有一个承诺,我希望它只有在内部承诺解决后才能解决。现在它在“loadend”回调中达到“resolve”函数之前解析。

我错过了什么?我对您应该使用 resolve 的方式以及如何在另一个 Promise 中使用 Promise 感到困惑。

我在网上找不到任何有帮助的东西。

在下面的示例中,我基本上加载了一堆文件,对于每个文件,我得到一个 blob,我想在文件阅读器中传递这个 blob。

将所有文件传递给文件阅读器后,我想转到承诺链中的下一个函数。

现在它进入链中的下一个函数,而无需等待调用 resolve。

var list = [];
var urls = this.files;

urls.forEach(function(url, i) {
    list.push(
        fetch(url).then(function(response) {
            response.blob().then(function(buffer) {

                var promise = new Promise(
                    function(resolve) {

                        var myReader = new FileReader();
                        myReader.addEventListener('loadend', function(e) {
                            // some time consuming operations
                            ...
                            window.console.log('yo');
                            resolve('yo');
                        });

                        //start the reading process.
                        myReader.readAsArrayBuffer(buffer);
                    });

                promise.then(function() {
                    window.console.log('smooth');
                    return 'smooth';
                });

            });
        })
    );
});

...

// run the promise...
Promise
    .all(list)
    .then(function(message){
        window.console.log('so what...?');
    })
    .catch(function(error) {
        window.console.log(error);
    });
4

1 回答 1

23

当你没有returnthen回调中做任何事情时,它假定同步操作并立即使用结果 () 解决结果承诺undefined

您需要对return每个异步函数做出承诺,包括then您想要链接的回调。

具体来说,您的代码应该成为

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';
            });
        })
    });
});

甚至更好,扁平化

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';
    });
});
于 2015-04-17T12:41:48.253 回答