簡體   English   中英

.then 范圍內的變量值與 .then 范圍外的變量值不同

[英]Variable value inside .then scope is different from variable value outside .then scope

我登錄的價值src變量中.then ,外.then ,我觀察到src都有不同的價值觀,我不知道為什么:

getUserPicSrc(){
        var src;
        var db=new window.PouchDB('http://127.0.0.1:5984/passport-test');
        db.getAttachment(this.props.store.user._id,'pic.jpg').then(blob=>{
            src=window.blobUtil.createObjectURL(blob);
            console.log('src inside then: '+src);// src inside then: blob:http://127.0.0.1:10002/ed1cf453-3902-4064-8966-e74c4a1ee6b4
        }).catch(error=>{
            console.log(error);
        })
        console.log('src outside then: '+src);// src outside then: undefined
        return src;
    }

更新

我最終這樣做了,效果很好:

setUserPicSrc(){
    var db=new window.PouchDB('http://127.0.0.1:5984/passport-test');
    db.getAttachment(this.props.store.user._id,'pic.jpg').then(blob=>{
        var url=window.blobUtil.createObjectURL(blob);
        console.log('url: '+url);
        document.getElementById('userPic').src=url;
    }).catch(error=>{
        console.log(error);
    })
}

非常簡單的答案:外部src變量首先運行並打印 undefined。 因為 http 調用尚未完成,因此未分配該值。 .then需要一點時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM