Javascript 函数应该返回字符串的承诺,但不返回
我正在尝试上载图像并返回其id,代码如下:Javascript 函数应该返回字符串的承诺,但不返回,javascript,node.js,typescript,Javascript,Node.js,Typescript,我正在尝试上载图像并返回其id,代码如下: export function uploadImage(file: any, location: string, next: any): Promise<string> { try { if (!file) { throw new Error("No Image file"); } const id = location + "/" + utilities.ge
export function uploadImage(file: any, location: string, next: any): Promise<string> {
try {
if (!file) {
throw new Error("No Image file");
}
const id = location + "/" + utilities.generatePushID();
const options = {
resource_type: "raw",
public_id: id,
};
return cloudinary.uploader.upload_stream(options, (error: any, result: any) => {
if (error) {
throw new Error("Couldn't upload");
}
return result.public_id;
}).end(file.buffer);
} catch (err) {
return next(InternalError(err));
}
}
但是,每当我尝试调用该函数时,它都会返回一个UploadStream对象,而不是我想要的字符串。这就好像它立即返回上传程序,而不是上传程序的结果。为什么?因为upload\u stream不会返回承诺,如果您想做出承诺,请尝试以下方法:
导出异步函数uploadImagefile:any,位置:string,下一步:any:Promise{
返回新的PromiseSolve,拒绝=>{
试一试{
如果!文件{
拒绝新的ErrorNo图像文件;
}
const id=location+/+utilities.generatePushID;
常量选项={
资源类型:原始,
公共id:id,
};
return cloudinary.uploader.upload\u streamoptions,错误:any,结果:any=>{
如果错误{
拒绝新错误无法上传;
}
resultresult.public\u id;
}.endfile.buffer;
}犯错误{
拒绝内部错误;
}
};
}
去掉next,因为它看起来像是一个回调,然后你可以像这样调用它:
const public_id=等待上传图像。。。;
//或
uploadImage…,然后public\u id=>console.logpublic\u id.catch=>console.error;
注意。这个.upload\u流调用看起来是基于回调的,而不是基于承诺的..?它似乎不喜欢它,给了我一个错误:[ts]类型“{}”不可分配给类型“string”。通过将承诺更改为承诺来修复错误,它可以工作:只是一个旁注-如果返回承诺,则不需要它是异步函数。它可以只是一个常规函数,返回一个承诺,并且仍然可以等待。