javascript - 如何让 Javascript 在移动到另一个函数之前等待一个函数完成?
问题描述
我对 Javascript 还很陌生,我需要帮助让我的代码等待函数完成,然后再继续下一个。在我的代码中,我使用 SES 发送电子邮件,并在 SNS 中发布主题。
发送电子邮件并发布主题后,我需要将用户导航到感谢页面。
就我的代码设置方式而言,这是非常不一致的。有时它会在导航之前发送电子邮件并发布,有时它会做一个或另一个然后导航。我需要帮助了解如何让代码在导航到不同页面之前等待这两个函数完成。
谢谢大家!
我尝试过使用 if 语句,但并没有像我想象的那样成功。
sns.publish(snsParams, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
ses.sendEmail(sesParams, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
window.location = 'https://abc123.com/contact/thanks/';
解决方案
您可以通过使用第二个调用作为对第一个调用的回调或通过承诺调用来做到这一点:
sns.publish(snsParams, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
}).promise().then(() => {
return ses.sendEmail(sesParams, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
}).promise().then(() => window.location = 'https://abc123.com/contact/thanks/'));
推荐阅读
- javascript - 如何在ajax调用的成功部分加载javascript文件
- plugins - java.lang.IllegalArgumentException:尝试从扩展向导运行多页编辑器后找不到 IDadditions
- python - 将列中的长列表转换为新的df
- android - RecyclerView中的按钮无法点击或选择
- linux - 从默认致命信号的信号处理程序返回
- python - 检查 python 列表是否遵循特定的重复模式
- python-3.x - Databricks python notebook 执行的日志文件
- mongodb - Mongodb - $in 模拟查询 AND,而不是 OR
- java - 为什么 SimpleJdbcCall igronre @Transactional 注解
- angular - innerHTML 的正确值并翻译 Angular