【问题标题】:Variable value inside .then scope is different from variable value outside .then scope.then 范围内的变量值与 .then 范围外的变量值不同
【发布时间】:2017-01-30 06:18:17
【问题描述】:

我在.then.then 之外记录src 变量的值,我观察到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);
    })
}

【问题讨论】:

标签: javascript


【解决方案1】:

非常简单的答案: 外部src 变量首先运行并打印未定义。因为 http 调用尚未完成,因此未分配值。 .then 需要一点时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2021-08-18
    • 2015-12-09
    相关资源
    最近更新 更多