- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 bluebirdjs 获得 promise 功能。但所有尝试都失败了,因为也许我不知道自己在做什么......?
我想获取文件位置,然后逐个下载文件,然后推送到数组。
import * as Promise from 'bluebird';
fileFunction(files){
Promise.map(files, function(file) {
// Promise.map awaits for returned promises as well.
//Promise.delay(1000);
return this.getLocation(file);
},
).then((file) => {
console.log('done')
});
}
getLocation(file){
if(file){
return this._storage.ref(file).getDownloadURL().subscribe(url =>
this.img_array.push(url)
);
}
当我调用 return this.getLocation(file)... 时,出现以下 错误
bluebird.js:1545 未处理的拒绝 TypeError: 无法读取未定义的属性“getLocation”...bluebird.js
编辑现在使用的部分代码!
fileFunction(files){
return Promise.map(files, file => {
return this.getDownloadUrl(file);
}).then(locations => {
// add these locations onto this.img_array
this.img_array.push(...locations);
console.log('done');
return locations;
});
}
getFiles(e): Promise<any>{
this.outPutFiles = e;
this.fileFunction(this.outPutFiles).then(locations => {
locations.map((arr) => arr.subscribe((files) => this.downloadUrls.push(files)));
}).catch(err => {
console.log(err);
});
}
getDownloadUrl(file){
if(file){
return this._storage.ref(file).getDownloadURL();
} else {
return Promise.reject(new Error('No file passed to getLocation'));
}
}
最佳答案
this.getLocation(file)
不起作用,因为您丢失了 this
的值,因为您位于 Promise.map()
回调。请记住,Javascript 中的每个正常函数调用都会更改 this
的值,除非您专门控制 this
的值。
您可以使用回调的简单箭头函数来修复该部分问题,如下所示:
fileFunction(files){
return Promise.map(files, file => {
return this.getLocation(file);
}).then(locations => {
// add these locations onto this.img_array
this.img_array.push(...locations);
console.log('done');
return locations;
});
}
这假设 this.getLocation(file)
返回一个解析为位置值的 Promise。你确定它能做到这一点吗?看起来您的问题可能不仅仅是您遇到的第一个错误。
并且,在闲聊之后,您还需要修复 getLocation()
以返回解析为所需 URL 的 Promise。查看 firebase Javascript 文档,似乎 getDownloadURL()
已返回解析为所需 URL 的 promise 。因此,您只需返回该 Promise 并让 Promise.map()
为您管理结果即可。
getLocation(file){
if(file){
return this._storage.ref(file).getDownloadURL();
} else {
return Promise.reject(new Error("No file passed to getLocation"));
}
}
<小时/>
然后你就可以像这样使用它:
obj.fileFunction(fileArray).then(locations => {
console.log(locations);
}).catch(err => {
console.log(err);
});
关于javascript - 如何在 bluebirdjs Promise 中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997313/
我是一名优秀的程序员,十分优秀!