gpt4 book ai didi

javascript - 如何.then链接,但需要前一个promise-JavaScript的resolve()值?

转载 作者:行者123 更新时间:2023-12-03 08:49:31 25 4
gpt4 key购买 nike

问题在于“backendLoginCheck”功能。我想在“getUserByEmail”之后将.then()链“ifUserIsDisabled”。但是我需要getUserByEmail的“userRecord”作为“ifUserIsDisabled”的输入。

我也希望两个函数在“backendLoginCheck”函数中共享相同的.catch。

当前代码:

function getUserByEmail(email){
return new Promise(function(resolve, reject){
firebase.serverAuthAdmin147th.getUserByEmail(email)
.then(function(userRecord) {
resolve(userRecord);
})
.catch(function (error) {
reject({token: null, errorCode: "auth/user-not-found"});
});
})
}

function ifUserIsDisabled(userRecord){
return new Promise(function(resolve, reject){
if(!userRecord.disabled){
resolve();
}
else{
reject({token: null, errorCode: "auth/user-disabled"});
}
})
}

function backendLoginCheck(email, password, callback){
var token = null;
var errorCode = null;
var uid = null;
getUserByEmail(email)
.then(function(userRecord){
ifUserIsDisabled(userRecord);
})
.catch(function(error){
callback(error);
});
}

期望的主意:
...
getUserByEmail(email)
.then(ifUserIsDisabled(userRecord))
.then(nextFunction())
.then(nextFunction2(uses_resolveVal_from_nextFunction))
.then(nextFunctionEtc())
.catch(function(error){
callback(error);
});

最佳答案

如果我正确地理解了您,则好像您快要到了。如果一个promise中的then链返回另一个promise,您可以将已解决的值向下传递

例如:

function firstFunction() {
return new Promise((resolve, reject) => {
if (someError) {
reject(firstErr)
} else {
resolve('first value')
}
})
}

function secondFunction() {
return new Promise((resolve, reject) => {
if (someError) {
reject(secondErr)
} else {
resolve('second value')
}
})
}

firstFunction()
.then((resolvedFirstValue) => {
return secondFunction()
})
.then((resolvedSecondValue) => {
console.log(resolvedSecondValue)
})
.catch((err) => {
// any error in the entire chain
console.error(err)
})

关于javascript - 如何.then链接,但需要前一个promise-JavaScript的resolve()值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44835613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com