1

I log the value of src variable inside .then and outside .then and I observe that src has different values, I wonder why:

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;
    }

UPDATE

I ended up doing this which works fine:

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);
    })
}
Megidd
  • 7,089
  • 6
  • 65
  • 142

1 Answers1

1

Very simple answer: The outside src variable runs first and prints undefined. Because the http call has not been completed yet and hence the value is not assigned. .then takes a small amount of time.

Shubhranshu
  • 511
  • 3
  • 12