暂停功能,直到另一个功能

时间:2018-10-13 19:59:44

标签: node.js asynchronous twilio

我在节点中有一个函数,负责注册新用户并将用户对象保存到数据库。但是,仅当用户请求SMS验证码,然后输入发送的正确代码时,才会发生这种情况。这是我当前流程的模型:

signUp(userData){
  sendVerificationCode()

  // after verifyCode() is called in the future and code is valid
  saveUserData()
}

sendVerificationCode(){
 // send a request to twilio which then sends an SMS to the user
}

verifyCode(){ 
 // send a request to twilio with the code and the response 
 // is whether the code is valid
}

signUp是第一个调用的函数,然后应调用sendVerificationCode函数,然后将来将调用verifyCode,只有这样signUp才能继续并保存用户数据。我怎样才能做到这一点?看来我需要暂停一个功能,直到另一个功能被调用。

2 个答案:

答案 0 :(得分:1)

我认为有比暂停函数执行更简单的方法。我了解您想要做的事情,并且有一些异步编写此方法的方法,可以让您做自己想做的事情。

这是一个非常简单的示例,可以在单个过程中完成您所描述的事情。它假定signUp将在用户尝试注册时被调用。然后调用sendVerificationCode,我认为它将触发Twilio向用户发送代码。 userData存储在database.pendingUsers中的内存中(您也可以使用数据库)。我们可以根据待批准的用户注册时提供的电话号码为其键入密钥。 signUp函数到此结束。

我认为下一步是让用户以某种方式输入代码作为我们程序的输入。当用户将代码提交回我们的脚本时(这部分取决于您,没有提供有关http,命令行或其他方式的详细信息),我们可以调用verifyCode。调用verifyCode时,我们将需要电话号码(在不知道用户如何与此代码交互的情况下,我无法提供有关如何获得此电话的建议)。我们可以验证Twilio提供的代码是否有效,请从pendingUsers获取用户详细信息,并将其保留到users。您可能为此使用了数据库,在这种情况下,您的代码看上去会有所不同,但是逻辑是相似的。

这是示例代码:

const database = {
  pendingUsers: {},
  users: {},
};

signUp(userData){
  database.pendingUsers[userData.phone] = userData;
  sendVerificationCode(userData.phone);
}

sendVerificationCode(phone) {
  // send a request to twilio which then sends an SMS to the user
}

verifyCode(message) {
  // you need to get a hold of the phone number this verification code is for
  const phone = message.from;

  // send a request to twilio with the code and the response 
  // is whether the code is valid

  const verified = ...; // verify code

  if (!verified) {
    return false;
  }

  const userData = database.pendingUsers[phone];

  if (userData) {
    // remove from pending
    delete database.pendingUsers[phone];
    // save user
    database.users.push(userData);
  }

}

答案 1 :(得分:0)

我认为您可以为该用例使用另一个近似值。在上一步中,客户端要求输入SMS代码,此时API调用结束。

第二分钟,客户端发送代码信息和用户信息,您验证代码,如果正确,则将用户信息保存在数据库中。

假设您正在使用NodeJS 8,则可以将verifyCode()声明为异步函数,并使用await verifyCode()等待响应。

例如:

// The first request of the client 
verificationCodeRequest(userData){
   sendVerificationCode()
}

signUp(userData){
   try {
     response = await verifyCode();  
     // Maybe, you need another validation
     if (isCodeCorrect) { 
        writeToDB(userData);
     } else {
       error();
     }
   } catch (err) {
     error();
   }


sendVerificationCode(){
 // send a request to twilio which then sends an SMS to the user
}

async verifyCode(){ 
 // send a request to twilio with the code and the response 
 // is whether the code is valid
}

希望我能理解您的问题,对于我的英语感到抱歉,我正在努力。

相关问题