栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

排队承诺

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

排队承诺

基本$ q链示例

是的,您 可以 使用Angular的$
q建立链式队列!这是一个示例,向您展示如何使用递归创建任何长度的队列。每个帖子都相继发生(一个接一个)。在第一篇文章完成之前,第二篇文章将不会开始。

这在写入数据库时​​可能会有所帮助。如果数据库在后端没有自己的队列,并且您同时进行多次写入,则可能会发现并非所有数据都已保存!

我添加了一个Plunkr示例来演示此代码的实际作用。

$scope.setData = function (data) {  // This array will hold the n-length queue  var promiseStack = [];  // Create a new promise (don't fire it yet)  function newPromise (key, data) {    return function () {      var deferred = $q.defer();      var postData = {};      postData[key] = data;      // Post the the data ($http returns a promise)      $http.post($scope.postPath, postData)      .then(function (response) {        // When the $http promise resolves, we also        // resolve the queued promise that contains it        deferred.resolve(response);      }, function (reason) {        deferred.reject(reason);      });      return deferred.promise;    };  }  // Loop through data creating our queue of promises  for (var key in data) {    promiseStack.push(newPromise(key, data[key]));  }  // Fire the first promise in the queue  var fire = function () {    // If the queue has remaining items...    return promiseStack.length &&    // Remove the first promise from the array    // and execute it     promiseStack.shift()()    // When that promise resolves, fire the next    // promise in our queue     .then(function () {      return fire();    });  };  // Begin the queue  return fire();};

您可以使用一个简单的函数开始队列。为了进行演示,我将一个充满键的对象传递给一个函数,该函数会将这些键拆分为各个帖子,然后将其发布到Henry的HTTP
Post Dumping
Server中。(感谢亨利!)

$scope.beginQueue = function () {  $scope.setData({    a: 0,    b: 1,        y: 24,    z: 25  }).then(function () {    console.log('Everything was saved!');  }).catch(function (reason) {    console.warn(reason);  });};

如果您想尝试此代码,请参见以下指向Plunkr示例的链接。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/401529.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号