我有一个承诺,我希望只有当内在的承诺已经解决时,它才能解决。现在,在“加载端”回调中到达“解析”函数之前,它将进行解析。
我遗漏了什么?我对你应该如何使用决心以及如何在另一个承诺中使用一个承诺感到困惑。
我在网上找不到任何有用的东西。
在下面的示例中,我基本上加载了一堆文件,对于每个文件,我会得到一个blob,并且我希望将这个blob传递到文件阅读器中。
一旦所有文件都被传递给文件读取器,我想转移到承诺链中的下一个函数。
现在,它将转到链中的下一个函数,而无需等待解析的调用。
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);
});发布于 2015-04-17 12:41:48
当您不从return回调中提取任何内容时,它将假设同步操作,并立即使用结果(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';
});
});https://stackoverflow.com/questions/29699372
复制相似问题