JavaScript 在 then 函数之外访问 Promise

5 javascript global-variables promise

我正在尝试使用 JavaScript 在 then 函数之外访问 Promise 中的值。我是 Promise 的新手,我不确定我是否做对了。这是我的代码:

//removed code
Run Code Online (Sandbox Code Playgroud)

基本上我已经将 Promise 返回的值存储到 then 函数内的一个单独变量中。我想在后面的部分访问它们,但是当我在后面的部分打印出来时,它返回我未定义。关于如何解决这个问题的任何想法?

我找到了一些例子并遵循了它们,但它不起作用。我不确定我的代码的哪一部分是错误的。我早些时候打开了一个线程,它被标记为重复并关闭。我想我的询问不够清楚,因此我在这里重新表述这个问题。

Ori*_*lom 2

为了在两个 Promise 解析它们的值时执行逻辑,您应该Promise.all()在 Promise 对象上使用 。

  Promise.all([promiseCurrencyKey, promiseStoreKey]).then(values => { 
    console.log(values); 
  });
Run Code Online (Sandbox Code Playgroud)

JavaScript 是一种单线程语言,这意味着让代码等待某件事发生将会阻塞其他一切。现在,如果没有有时可能需要一段时间的东西,我们就无法真正编码,这就是 Promise 的用途。

Promise 中的逻辑正在后台处理,不会阻塞代码。为了使用由 Promise 解析的值,您可以在then()解析值时执行的方法中设置一个回调函数。

在解析值时执行回调不会使其余代码等待。

因此,描述您的代码发生的情况如下:

  1. 在后台运行一些解析值的逻辑
  2. 当值解析时将其设置为 p1
  3. print p1 -步骤 1 中的 logc 尚未完成,这意味着 then 函数中的逻辑也没有发生,并且值仍未设置到 p1 中

p2 也发生同样的情况。

现在,当您使用时,Promise.all()您是在两个简单的空变量上执行它,而不是在 Promise 对象上执行,因此结果是带有两个空变量的数组......

在编辑后的第二个示例中,问题是您在第一个 Promise 函数中定义了 PromiseBranchKey,因此它仅存在于该函数的范围内,而不是在您调用的范围之外Promise.all()

let promiseMerchantKey = new Promise((resolve, reject) => {
    firebase.database().ref('merchants').orderByChild('merchantName').equalTo('NTUC').once('value', function(snapshot) {
        let merchantData = snapshot.val();
        if (merchantData){
            console.log('merchant exists');
            resolve(merchantData.key);
        }else{
            // get merchant unique push ID
            let merchantKey = firebase.database().ref('merchants').push({
                address : "NTUC"
            }).getKey();
            resolve(merchantKey);
        }
    });
});

let promiseBranchKey = new Promise((resolve, reject) => {
    firebase.database().ref('merchants').orderByChild('branchAddress').equalTo('Blk 167').once('value', function(snapshot) {
        let branchData = snapshot.val();
        if (branchData){
            console.log('branch exists');
            resolve(branchData.key);
        }else{
            // get branch unique push ID
            promiseMerchantKey.then((merchantKey) => {
                let branchKey = firebase.database().ref('merchants').child(merchantKey).push({
                    branchName : 'Marsiling',
                    branchAddress : 'Blk 167'
                }).getKey();
                resolve(branchKey);
            });
        }
    });
});

promiseBranchKey.then((branchKey) => { 
    console.log('branchkey' + branchKey); 
    console.log('currencykey' + promiseMerchantKey);
});
Run Code Online (Sandbox Code Playgroud)

考虑到 Promise 2 取决于 Promise 1 解析的值,您应该在then()其中使用该方法,并导致 Promise 2 的解析仅在第一个 Promise 已返回值时发生。

因为只有在 Promise 1 已经解决的情况下才能解决 Promise 2,所以没有必要promise.all(),我们可以在 Promise 2 上使用 then 来指示它们何时被处理。