Nic*_*las 8 javascript resolve promise ecmascript-6 es6-promise
我有一个承诺,我希望它只有在内心承诺得到解决时才能解决.现在它在"loadend"回调中达到"resolve"功能之前解析.
我错过了什么?我对你应该如何使用决心以及如何在另一个承诺中使用承诺感到困惑.
我在网上找不到任何有用的东西.
在下面的例子中我基本上加载了一堆文件,对于每个文件,我得到一个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);
});
Run Code Online (Sandbox Code Playgroud)
Ber*_*rgi 21
如果您没有回调return任何内容then,它会假定同步操作并undefined立即使用result()解析结果保证.
您需要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';
});
})
});
});
Run Code Online (Sandbox Code Playgroud)
甚至更好,扁平化:
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';
});
});
Run Code Online (Sandbox Code Playgroud)