如何从单个函数调用完成后执行连续if语句?



我试图连接到3 api的,但从一个按钮点击基本上-我希望每个进程开始前已经完成后。但是,目前它只执行第一个if语句,而不运行后面两个。

我应该采取不同的方法吗?

const syncAccount = () => {
if(!mavenlinkConnected){
getMavenlinkAuthorization()
}
if (!bambooConnected){
authorizeBamboo();
}
if (!maconomyConnected){
authorizeMaconomy();
}
}

下面是与上述代码块

相关的其他函数
useEffect(() => {
if (loading) return;
if (!user) return navigate("/");
fetchUserName();
if(userTokenCode !== null){
authorizeMavenlink();
}
}, [user, loading]);

const authorizeMavenlink = () => {
console.log(uid);
const userRef = doc(db, 'users', uid);
axios({
method: 'post',
url: 'http://localhost:5000/oauth/mavenlink?code='+userTokenCode,
data: {}
})
.then((response) => {
setAccessToken(response.data);
setDoc(userRef, { mavenlinkAccessToken: response.data}, { merge: true });
setMavenlinkConnected(true);
setSuccessAlert(true);
})
.catch((error) => {
console.log(error);
setErrorAlert(true)
});
}
const getMavenlinkAuthorization = () => {
window.open('https://app.mavenlink.com/oauth/authorize?client_id=********&response_type=code&redirect_uri=http://localhost:3000');
window.close();
}
const authorizeBamboo = () => {
// axios({
//     method: 'post',
//     url: 'http://localhost:5000/oauth/bamboo',
//     data: {}
// })
// .then((response) => {
//     console.log(response)
// })
// .catch((error) => {
//     console.log(error);
// });
console.log('bamboo connected')
setBambooConnected(true);
}
const authorizeMaconomy = () => {
console.log("Maconomy connected")
setMaconomyConnected(true);
}

正如你所说的,你正在调用每个if语句上的API您应该将函数标记为async,并等待每次执行。例子:-

const syncAccount = async() => {
if(!mavenlinkConnected){
await getMavenlinkAuthorization()
}
if (!bambooConnected){
await authorizeBamboo();
}
if (!maconomyConnected){
await authorizeMaconomy();
}
}

或者使用promises

const syncAccount = () => {
if(!mavenlinkConnected){
getMavenlinkAuthorization().then({
if (!bambooConnected){
return authorizeBamboo();
} else {
return Promise.resolve();
}
}).then(() => {
if (!maconomyConnected){
return authorizeMaconomy();
}
}).catch(error => {
//log error
})
}
}
祝你好运!快乐编码…

最新更新