在内心承诺解决之前承诺解决

时间:2015-04-17 12:34:18

标签: javascript promise ecmascript-6 resolve es6-promise

我有一个承诺,我希望它只有在内部承诺得到解决时才能解决。现在它在"解决"之前解决了。功能已经在" loadend"回调。

我错过了什么?我对你应该如何使用决心以及如何在另一个承诺中使用承诺感到困惑。

我无法在网上找到任何有用的东西。

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

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

现在它转到链中的下一个函数,而不等待调用解析。

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

1 个答案:

答案 0 :(得分:21)

当你没有return来自then回调的任何内容时,它会假定同步操作并立即使用结果(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';
            });
        })
    });
});

甚至更好,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';
    });
});
相关问题