为了在两个Promise对象都返回结果时执行逻辑,应该使用
Promise.all()
方法。
Promise.all([promiseCurrencyKey, promiseStoreKey]).then(values => {
console.log(values);
});
JavaScript是一种单线程语言,这意味着当代码等待某些事件发生时会阻塞其他所有代码的执行。但我们实际上不能没有有时需要一段时间才能完成的任务,这就是Promise的作用所在。
Promise中的逻辑在后台运行,不会阻塞代码的执行。为了使用Promise解析出的值,可以将回调函数设置到then()方法中,该函数将在值解析时执行。
回调函数的执行不会使其他代码等待。
因此,代码的运行过程如下:
1.在后台运行某些逻辑,以解析值
2.当值被解析时,将其设置为p1
3.打印p1 - 步骤1中的逻辑尚未完成,这意味着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{
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{
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);
});
考虑到 Promise 2 依赖于 Promise 1 返回的值,因此您应该在 Promise 2 中使用 then()
方法,并且只有当第一个 Promise 已经返回值时才会导致 Promise 2 的解决。
由于只有在 Promise 1 已经解决时才能解决 Promise 2,所以不需要使用 promise.all()
,我们可以在 Promise 2 上使用 then 来指示它们都已被处理。