[英]Clarification on order of Promise resolution using Async/Await
[英]JS promise/async clarification questions
我讀過一些關於諾言的文檔,並且有一些基本問題,因為一段時間以來我讀到這是真的,有時不是。
我有兩個問題/澄清
一個例子會很有幫助
- 如果Java腳本中的每個函數都可以使用promise進行調用(使用then),或者我應該從函數中返回一些promise對象,即可以通過在返回函數中添加一些Q來進行不同的定義?
承諾使用返回值。 如果一個函數沒有返回承諾-將其鏈接到另一個承諾將不會等待任何東西。 鏈(或類似.all
的集合)知道何時完成函數的方式是使用返回值。
function fn1(){
setTimeout(function(){ console.log("Hi"); }, 1000);
}
Promise.resolve.then(function(){ // start empty ES6 promise chain
return fn1();
}).then(function(){
console.log("Bye"); // this will log "Bye Hi" because it did not wait.
});
正確的方法是使它散布 :
function fn2(){ // in Angular which you tagged, this is similar to `$timeout`
return new Promise(function(resolve, reject){
setTimeout(function(){ console.log("Hi"); resolve(); }, 1000);
});
}
Promise.resolve.then(function(){ // start empty ES6 promise chain
return fn2();
}).then(function(){
console.log("Bye"); // this will log "Bye Hi" because it did not wait.
});
- 我看到有鏈許諾的選項,也可以做答。所有它們之間有什么不同
ES6中的Q.all或Promise.all是並行的,鏈接承諾是順序的:
Promise.all([fn1(), fn2(), fn3]).then(function(){
// fn1 fn2 and fn3 complete at an arbitrary order
// code here executes when all three are done
});
fn1().then(fn2).then(fn3).then(function(){
// fn1 executes, when it is done fn2, when it is done fn3,
// then code here
});
- 有某種工具或某種方式可以驗證諾言是否被鏈接好嗎? 因為當我嘗試錯誤地忘記某些鏈函數中的return語句時,這可能會損害過程。
是的,不久前Spion為此編寫了一個工具,它稱為thenlint
,您可以在此處找到它。 描述說:
承諾的皮棉紙,檢查可能的Promise.then使用錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.