相关疑难解决方法(0)

为什么我的变量在函数内部修改后没有改变? - 异步代码引用

鉴于以下示例,为什么outerScopeVar在所有情况下都未定义?

var outerScopeVar;

var img = document.createElement('img');
img.onload = function() {
    outerScopeVar = this.width;
};
img.src = 'lolcat.png';
alert(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)

var outerScopeVar;
setTimeout(function() {
    outerScopeVar = 'Hello Asynchronous World!';
}, 0);
alert(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)

// Example using some jQuery
var outerScopeVar;
$.post('loldog', function(response) {
    outerScopeVar = response;
});
alert(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)

// Node.js example
var outerScopeVar;
fs.readFile('./catdog.html', function(err, data) {
    outerScopeVar = data;
});
console.log(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)

// with promises
var outerScopeVar;
myPromise.then(function (response) {
    outerScopeVar = response;
});
console.log(outerScopeVar);
Run Code Online (Sandbox Code Playgroud)

// geolocation API
var outerScopeVar; …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous

675
推荐指数
6
解决办法
18万
查看次数

如何在.then()链中访问先前的promise结果?

我已经将我的代码重组为承诺,并构建了一个由多个回调组成的精彩长扁平承诺链.then().最后我想返回一些复合值,并且需要访问多个中间承诺结果.但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?

function getExample() {
    return promiseA(…).then(function(resultA) {
        // Some processing
        return promiseB(…);
    }).then(function(resultB) {
        // More processing
        return // How do I gain access to resultA here?
    });
}
Run Code Online (Sandbox Code Playgroud)

javascript scope promise bluebird es6-promise

607
推荐指数
10
解决办法
18万
查看次数