简体   繁体   English

无法在 then 方法中调用 function

[英]Cannot call a function inside a then method

I am trying to call two functions one within another我试图在另一个中调用两个函数

commonService Components公共服务组件

function AddEmail(user) {
    return auth.createUserWithEmailAndPassword(user.email,user.password);    
    //createUsers(user) this way of calling is working, but i don't want to invoke like this...
}

function createUsers(user) {
    return db.collection("users").add({
        firstName: user.firstName,
        lastName:  user.lastName,
        address:  user.address,
        phoneNumber:  user.phoneNumber,
        email:  user.email,
        role:  user.role,
    });
}

register component注册组件

submits(e) { 
    e.preventDefault();
    const { user} = this.state;
        
    commonService.AddEmail(user)
    .then(() => {
        commonService.createUsers(user)
        .then(() =>{//success})
        .catch(err=> console.log(err));
    })
    .catch(err=> console.log(err));
}

The AddEmail gets executed, but not the createUsers . AddEmail被执行,但不是createUsers I've tried returning and chaining via then method too, still its not working, what am I missing?我也尝试过通过then方法返回和链接,仍然无法正常工作,我错过了什么?

Try the following with async / await .使用async / await尝试以下操作。

async submit(e){
    e.preventDefault();
    const { user} = this.state;

    try {
        const userEmailAdded = await commonService.AddEmail(user);
        const userCreated = await commonService.createUsers(user);
    } catch (err) {
        console.log(err);
    }
}

Make sure to return a promise in both the function calls.确保在 function 调用中都返回 promise。 If the return value is not a promise, wrap it in a promise using the following code如果返回值不是 promise,则使用以下代码将其包装在 promise 中

function AddEmail(user) {
    return new Promise((resolve, reject){
        const createdUser = auth.createUserWithEmailAndPassword(user.email,user.password);
        if(createdUser)
            return resolve(createdUser);
        else
            return reject("Error in creating user.");
    })
}

Check for any errors in console.检查控制台中的任何错误。 If none, both calls passed.如果没有,两个调用都通过了。

Try to use this code.尝试使用此代码。

submits(e) { 
    e.preventDefault();
    const { user} = this.state;
        
    commonService.AddEmail(user)
    .then(() => commonService.createUsers(user))
    .then(() =>{//success})
    .catch(err=> console.log(err));
}
return auth.createUserWithEmailAndPassword(user.email,user.password);

The returning function must be a javascript Promise to use a .then .返回的 function 必须是 javascript Promise才能使用.then

You can try to console.log(auth.createUserWithEmailAndPassword) whether it is a Promise or not.您可以尝试console.log(auth.createUserWithEmailAndPassword)是否是 Promise。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM