我正在构建一个聊天机器人,该聊天机器人从聊天中获取消息,并将其发送到api,该api根据消息生成随机的gif。
axios请求/响应正常工作,但是我需要它来将响应中的URL值存储为外部变量。
然后将使用其他功能在聊天中发送变量/ URL。此函数无法在axios request / then语句中运行,我似乎也无法从其中之一获取要更新的变量。
我对此有些困惑,还没有找到可以满足我需要的方法。任何建议表示赞赏。
How do I return the response from an asynchronous call?并未解决如何从外部获取此消息,因为再次无法从then语句内部运行message函数。
const sentence = context.activity.text.replace('!guggy ', '');
//theoretically this would hold the api response, but this wont update as intended
//var apiResponse;
//api call function
function postRequest(x) {
return axios.post('http://exampleurl.here.com/helpapi', {
"sentence" : x,
"lang": "ru"
},{
headers: {
"Content-Type":"application/json",
"apiKey":"example-key-2020202"
}
});
}
//initiates api call, then logs response or error
postRequest(sentence).then(function(response) {
console.log(response.data.animated[0].gif.original.url); //this works, returns URL
//attempting to store the same value as external variable doesnt work
apiResponse = response.data.animated[0].gif.original.url; //the variable remains blank when called later
}).catch (function (error) {
console.log(error);
});
//this has to be run outside of axios/then statement, or it will not work.
//this should take the url passed from the response, and send it as a chat message
await context.sendActivity(apiResponse);
这实际上不返回任何错误,并且在服务器上运行。当我需要它时,它只是不返回变量-它的空白。我以为这意味着我只是忽略或误解了一些关键内容。
答案 0 :(得分:0)
代码段中的执行顺序为:
$message = "
<h2>Thank you for Registering.</h2>
<p>Your Account:</p>
<p>Email: ".$email."</p>
<p>Password: ".$_POST['password']."</p>
<p>Please click the link below to activate your account.</p>
<a href='".$_SERVER['HTTP_HOST']."/activate.php?code=".$code."&user=".$userid."'>Activate Account</a>";
$mail = new PHPMailer(true);
try {
//Server settings
$mail->isSMTP();
$mail->Host = 'smtp.mailtrap.io';
$mail->SMTPAuth = true;
$mail->Username = 'e0891ddb9b14a1';
$mail->Password = '373f8f6c93f27d';
$mail->Port = 465;
$mail->setFrom('jeraldpunxbot1@gmail.com');
//Recipients
$mail->addAddress($email);
$mail->addReplyTo('jeraldpunxbot1@gmail.com');
//Content
$mail->Subject = 'ShopNow Sign Up';
$mail->Body = $message;
$mail->isHTML(true);
$mail->send();
unset($_SESSION['firstname']);
unset($_SESSION['lastname']);
unset($_SESSION['email']);
$_SESSION['success'] = 'Account created. Check your email to activate.';
header('location: signup.php');
} catch (Exception $e) {
$_SESSION['error'] = 'Message could not be sent. Mailer Error: '.$mail->ErrorInfo;
header('location: signup.php');
}
用空白的context.sendActivity()
调用。apiResponse
被分配了。您需要适当地等待服务器返回错误,如下所示:
apiResponse