亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

同步調用 javascript promise

同步調用 javascript promise

料青山看我應如是 2023-05-11 14:40:34
我試圖在我的程序完成并發送郵件之前在數據庫中插入一條記錄。但問題是我認為我的函數正在異步運行,在我收到成功插入數據庫的成功消息之前,我的程序已完成并且 te 永遠不會拋出錯誤。以下是我嘗試過的。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;};Async并且await因為我們使用的是 ES6 而無法正常工作。關于如何使我的承諾調用同步的任何建議都會有所幫助。發送激活郵件正在調用不同的承諾,并且不是同一鏈的一部分。Client.sendAccountActivationMail(u).then(function(data) {            var isSuccess = angular.fromJson(data);            if (isSuccess) {            }         });
查看完整描述

1 回答

?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

如果您從回調內部返回一個非承諾值.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: '[email protected]' })

  .then(() => console.log("All done."));


查看完整回答
反對 回復 2023-05-11
  • 1 回答
  • 0 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號