简体   繁体   English

Promise 在定义嵌套 object 属性之前解析

[英]Promise resolving before nested object property is defined

I am trying to return an object with two properties... one which is generating a blob, and requires time to resolve.我正在尝试返回一个具有两个属性的 object...一个正在生成 blob,需要时间来解决。 However javascript seems to jump to the next function (or 'link' in the chain') before the promise is resolved.然而,在 promise 解决之前,javascript 似乎跳转到下一个 function(或链中的“链接”)。 Is there any way I can make it wait for this nested property to resolve before jumping to the next function?有什么办法可以让它在跳转到下一个 function 之前等待这个嵌套属性解析?

fetch(prefix + '/download', {
    method: 'POST',
    .....
})
.then((response) => {
    var contentDisposition = response.headers.get('content-disposition');
    var fileName = contentDisposition.split('filename=')[1].split(';')[0];
    return { blob: response.blob(), filename: fileName }
})
.then((blob) => {
    return { href: URL.createObjectURL(blob.blob), filename: blob.filename }
})

I receive Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.我收到Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided. , presumably because blob.blob returns a Promise and has no value yet. ,大概是因为 blob.blob 返回 Promise 并且还没有值。

Try returning the response.blob() promise with it's own then() to return the final data尝试用它自己的then()返回response.blob() promise 以返回最终数据

fetch(prefix + '/download', {
    method: 'POST',
    .....
})
.then((response) => {
    var contentDisposition = response.headers.get('content-disposition');
    var filename = contentDisposition.split('filename=')[1].split(';')[0];

     return response.blob().then(blob =>{
        return  { href: URL.createObjectURL(blob), filename}
     });    
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM