繁体   English   中英

同步调用 javascript 承诺

[英]Make Syncronous call to javascript promise

我试图在我的程序完成并发送邮件之前在数据库中插入一条记录。 但问题是我认为我的函数是异步运行的,在我收到成功插入数据库的成功消息之前,我的程序已经完成,并且永远不会抛出错误。 以下是我尝试过的。

Client.insertUser(sendInfo)
  .then(
    function (Data) {
      if (Data == null || Data.User == null || Data.isPersonaUpdated == false) {
        $state.go('register.failed');
      }
    }
  )
  .catch(
    function () {
      $state.go('register.failed');
    }
  )

客户端.js

_this.insertUser = function (sendInfo) {
  var deferred = $q.defer();
  $http({
    method: 'POST',
    url: Globals.userAuth ? 'InsertUser.go' : 'modules/guest/InsertUser.go',
    data: sendInfo,
    headers: {
      'Content-type': 'application/json'
    }
  }).then(function successCallback(response) {
    deferred.resolve(response.data);
  }, function errorCallback(response) {
    deferred.reject(response);
  });

  return deferred.promise;
};

由于我们使用的是 ES6,因此Asyncawait不起作用。 关于如何使我的承诺调用同步的任何建议都会有所帮助。

发送激活邮件正在调用不同的承诺,并且不是同一链的一部分。

Client.sendAccountActivationMail(u).then(function(data) {
            var isSuccess = angular.fromJson(data);
            if (isSuccess) {
            }
         });

如果你从.then回调中返回一个非承诺值,那么它会自动被包装在一个承诺中。 这甚至适用于undefined的默认返回值。

这意味着您可以使用 if 语句有条件地创建用户。

 function logIn({ shouldCreateUser, username, emailAddress }) { console.log("In logIn..."); return Promise.resolve() .then(() => { console.log("In first then..."); if (shouldCreateUser) { return createUser(username); // ! } // If control moves here, a promise is implicitly returned with a value of `undefined` }) .then(() => { console.log("In second then..."); return client.sendEmail(emailAddress); // send email to everyone }) .then(() => { console.log("Continuing with application logic..."); }) .catch((err) => { console.error(err.message); //catch any unhandled promise exceptions }); } function createUser(username) { console.log("In createUser..."); return client .insertUser(username) .then((result) => { if (!result || !result.user || !result.isPersonaUpdated) throw new Error("User insertion failed"); console.log("User created asynchronously ok..."); }) .catch((err) => { console.error("Error thrown in createUser...", err.message); }); } const client = { insertUser() { return Promise.resolve().then(() => ({ user: {}, isPersonaUpdated: true })); }, sendEmail() { console.log("Sending email..."); return Promise.resolve().then(() => console.log("Email sent asynchronously ok...") ); } }; // Try flipping the value of `shouldCreateUser` logIn({ shouldCreateUser: true, username: 'Fred Bloggs', emailAddress: 'example@example.com' }) .then(() => console.log("All done."));

暂无
暂无

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

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