我有一个疑问..如果在promise的.then()
之前定义变量,我可以在.then()
中使用它们,对吗?对于回调而言,情况并非如此,但应使用q
Promise。
为确保这一点,我问以下代码是否正确,即使在有多个请求的情况下。
因此,第二个arg2
的.then()
始终是正确的,而不是最后一次调用myapp()的arg2
。
function myapp()
{
var arg1=1;
var arg2=undefined; // loaded async
var arg3=undefined; // loaded async
call_promise(arg1)
.then(function(data)
{
arg2 = data;
})
.then(function()
{
arg3 = call_function(arg2);
console.log(arg3);
})
.catch(function(err){});
}
最佳答案
是的,那行得通。无论调用该函数多少次,都会在该函数中创建新变量。并且由于闭包属性,传递给then
处理程序的函数仍将能够访问arg2
和arg3
。
但是,执行此操作的正确方法是通过返回值来解析then
处理程序返回的promise,如下所示
function myapp() {
var arg1 = 1;
return call_promise(arg1)
.then(function(data) {
return data;
}).then(function(arg2) {
console.log(call_function(arg2));
}).catch(function(err) {});
}
关于javascript - 与链式Q promise异步加载的局部变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36033639/