使用链式 Q 承诺异步加载的局部变量

local variables loaded asynchronously with chained Q promises

本文关键字:异步 加载 局部变量 承诺      更新时间:2023-09-26

我有一个疑问.. 如果我在承诺.then()之前定义变量,我会在.then()中提供它们,对吗?回调不是这样,但它应该使用q承诺。

为了确保这一点,我问下面的代码是否正确,即使在多个请求的情况下也是如此。

因此,第二个.then()arg2总是正确的,它不是最后一次调用 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){});
}

是的,那会起作用。无论调用函数多少次,函数中都会创建新变量。并且由于 closure 属性,传递给then处理程序的函数仍然能够访问 arg2arg3

但是,执行此操作的正确方法是通过返回值来解决then处理程序返回的承诺,如下所示

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