gpt4 book ai didi

javascript - 排队 promise

转载 作者:数据小太阳 更新时间:2023-10-29 05:26:20 26 4
gpt4 key购买 nike

我使用 mbostock/queue用于排队一些异步操作。更多的是速率限制(UI 生成的事件很少,后端可以慢慢处理),并确保它们按顺序处理。我像这样使用它

function request(d, cb) {
//some async oper
add.then(function(){
cb(null, "finished ")
})
}

var addQ = queue(1);
addQ.defer(request) //called by few req at higher rates generated by UI

我已经使用 angular.js $q 进行异步操作。那么,我是必须使用 mbostock/queue,还是可以用 $q 构建一个队列(本质上是 https://github.com/kriskowal/q)

谢谢。

最佳答案

基本的 $q 链示例

是的,您可以使用 Angular 的 $q 构建链式队列!下面是一个示例,向您展示了如何使用递归来创建任意长度的队列。每个帖子都是连续发生的(一个接一个)。在第一个帖子完成之前,第二个帖子不会开始。

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

我添加了一个 Plunkr example演示此代码的实际效果。

$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's HTTP Post Dumping Server。 . (感谢 Henry !)

$scope.beginQueue = function () {

$scope.setData({
a: 0,
b: 1,
/* ... all the other letters of the alphabet ... */
y: 24,
z: 25

}).then(function () {

console.log('Everything was saved!');

}).catch(function (reason) {
console.warn(reason);
});
};

这是 Plunkr example 的链接如果您想试用此代码。

关于javascript - 排队 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21799269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com