Promise return 数据不能赋值给 class 变量?

Promise return data cannot be assigned to class variable?

我正在尝试将 promise 返回值赋给一个变量,但它没有赋值。当我 console.log(this.imageref1) 时,我仍然得到空字符串。 这里的objective是获取上传照片到firebase后返回的data.downloadURL。我需要下载的 URL。将其存储在我的数据库中作为图像路径。我被困在这里,我的数据库获取下载 URL 的空数据。

post_news(form: NgForm){

    this.title = form.value.title;
    this.content = form.value.content;
    this.category = form.value.category;


    console.log(this.capturedimage1);


    if(this.capturedimage1 !== ''){

        //console.log('captured image is not empty');



    let storageRef = firebase.storage().ref();

    const filename = Math.floor(Date.now() / 1000);

    const imageRef = storageRef.child(`images/${filename}.jpg`);

    let uploaded_file_path = `images/${filename}.jpg`;      


    imageRef.putString(this.capturedimage1, firebase.storage.StringFormat.DATA_URL).then(data=>{

        this.imageref1 = data.downloadURL;

    });


    } 
}
var that = this;
imageRef.putString(this.capturedimage1, firebase.storage.StringFormat.DATA_URL)
.then(data=>{      
    that.imageref1 = data.downloadURL;
    return Promise.resolve(data.downloadURL);
})
.then(function(url){
    //make the db call.
});

所以这个值最终会被设定。您可能正在努力解决它发生在封闭函数执行完毕之后的事实。例如,这是一个非常简单的测试用例:

function test(x) { 
  x.a = 1;
  Promise.resolve(true).then(_ => x.b = 2); 
  console.log(x);
}

操作,

> test({c: 3})
{ c: 3, a: 1 }
undefined

记录其中还没有 b: 2 的对象,然后 returns undefined。当然,最终设置了该参数:

> test(abc = {c: 3})
{ c: 3, a: 1 }
undefined
> abc
{ c: 3, a: 1, b: 2 }

要了解真正发生的事情,您需要了解所有 JS 都发生在 "event loop." JavaScript 内一次只允许一件事发生,因此当您安排其他事件发生时, JS要遵守规则,"do everything in this function first, and then find something else that's been scheduled to happen."

一些函数调用同步发生,它们阻止函数调用前进直到它们完成。例如,[1,2,3].forEach(x => console.log('hello, ' + x)) 将在完成前将 3 个字符串记录到控制台。但是 promised 值的全部意义在于计算机正忙于计算它,它还不可用。因此,您只能在发现该值后实际使用该值,并且您对 promise 的所有操作(包括向 .then().catch() 添加侦听器)都是异步非阻塞。当前函数完成并且那些回调被放入事件循环,只要承诺的计算完成就会发生。