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" callback.
What am I missing? I am confused about the way you are supposed to use resolve and about how you can use a promise within another promise.
I couldn't find anything that helped on the web.
In the following example I basically load a bunch of files, for each file I get a blob and I want to pass this blob in a file reader.
Once all files have been passed to the file reader, I want to move to the next function in the promise chain.
Right now it goes to the next function in the chain without waiting for resolve to be called.
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);
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…