简体   繁体   English

同步调用 javascript 承诺

[英]Make Syncronous call to javascript promise

I am trying to insert a record in DB before my program completes and sends mail.我试图在我的程序完成并发送邮件之前在数据库中插入一条记录。 But the issue is I think my function is running in async and before I get a success message for successful insert in DB my programs complete and te never throws an error.但问题是我认为我的函数是异步运行的,在我收到成功插入数据库的成功消息之前,我的程序已经完成,并且永远不会抛出错误。 Below is what I have tried.以下是我尝试过的。

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

Client.js客户端.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;
};

Async and await is not working since we are using ES6.由于我们使用的是 ES6,因此Asyncawait不起作用。 Any suggestion on how can I make my promise call syncronous will be helpful.关于如何使我的承诺调用同步的任何建议都会有所帮助。

Send Activation mail is calling a differnet promise and is not a part of the same chain.发送激活邮件正在调用不同的承诺,并且不是同一链的一部分。

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

If you return a non-promise value from inside a .then callback, then it will automatically be wrapped in a promise.如果你从.then回调中返回一个非承诺值,那么它会自动被包装在一个承诺中。 This will even work for the default return value of undefined .这甚至适用于undefined的默认返回值。

This means that you can use an if-statement to conditionally create the user.这意味着您可以使用 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