[英]Jquery - Chain functions with deferred and promises but without setTimeout
[英]What is the right way to use deferred angular promises with or without jquery?
沒有角度或打字稿,我有以下代碼:
let queue = [
function () {
let waitingTime = 0 ;
setTimeout(function () { console.log("a - " + Date.now()); }, waitingTime); },
function () {
let waitingTime = 2500 ;
setTimeout(function () { console.log("b - " + Date.now()); }, waitingTime); },
function () {
let waitingTime = 5000 ;
setTimeout(function () { console.log("c - " + Date.now()); }, waitingTime); }
];
function SerialCall(queue) {
var d = $.Deferred().resolve();
while (queue.length > 0) {
d = d.then(queue.shift()); // you don't need the `.done`
}
}
SerialCall(queue);
我想在 angular8 中復制它,並在組件內部打字。 我試過 npm 安裝 jquery 和 npm i @types/jquery。 我在“d = d”行中看到以下錯誤:
(local var) d: JQuery.Deferred<any, any, any>
Type 'PromiseBase<never, never, never, never, never, never, never, never, never, never, never, never>' is missing the following properties from type 'Deferred<any, any, any>': notify, notifyWith, reject, rejectWith, and 2 more.ts(2740)
做我想做的事情的正確方法是什么? (執行隊列中的第一個函數,完成后執行第二個,然后執行第三個)。 如果有一個更優雅的 angular only/javascript 方式,則不必使用 jquery,如果有另一個眾所周知的標准庫並且適用於我正在嘗試做的事情,那么這是一個可以接受的答案。
您的示例可以使用concat函數使用 observable 來完成。
const queue = [
defer(() => of(new Date()).pipe(delay(0)),
defer(() => of(new Date()).pipe(delay(2500)),
defer(() => of(new Date()).pipe(delay(5000))
];
concat(...queue).subscribe(console.log);
concat 函數按照它們完成的順序從 observable 發出值。
Observables 是 Angular 中 Promise 的首選替代品,你基本上可以做你以前用 Promises 做的所有事情,以及更多。
Promise 是基於拉取的值被解析。 Observable 是基於推送的值的發射位置。 后者允許聲明式編程,您可以在其中描述如何修改數據流。
一些關於 observables 的教程:
https://www.javascripttuts.com/introduction-to-angular-2-observables/ https://blog.logrocket.com/understanding-rxjs-observables/ https://medium.com/@kevinwkds/angular-observable -81eea33a1aab
如果您正在尋找使用 Promises 的方法(如標題所示),那么您可以執行以下操作:
// Let's stick to your original functions array
const queue = [
function () {
let waitingTime = 0 ;
setTimeout(function () { console.log("a - " + Date.now()); }, waitingTime); },
function () {
let waitingTime = 2500 ;
setTimeout(function () { console.log("b - " + Date.now()); }, waitingTime); },
function () {
let waitingTime = 5000 ;
setTimeout(function () { console.log("c - " + Date.now()); }, waitingTime); }
];
// you'll need this for the .reduce call
const starterPromise = Promise.resolve(null);
// Our Async wrapper
function asyncRunner(fn) {
return (new Promise(resolve => { resolve(fn()) }));
}
// and finally the reducer
await queue.reduce(
(p, fn) => p.then(() => asyncRunner(fn)),
starterPromise
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.