首页 > 解决方案 > 如何让 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/';

标签: javascript

解决方案


您可以通过使用第二个调用作为对第一个调用的回调或通过承诺调用来做到这一点:

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/'));

推荐阅读