簡體   English   中英

NodeJS承諾解決

[英]NodeJS promise resolution

const a = [1, 2, 3, 4, 5];

const f = () => new Promise((resolve, reject) => resolve(4));

const g = () => {
  Promise.all(a.map((member) => f().then((res) => res)))
    .then((result) => {
      console.log(result)
    });
}

g();

為什么我不需要另一個附加到{return res;}這里?

我讀到當你在一個內部有一個return (something) ,另一個then必須附加,但這不是這里的情況。 救命?

Promise.all期待一系列承諾。 .then返回一個承諾。 因此,您的映射邏輯會將數字數組轉換為Promises數組,這正是您所需要的。

.then((res) => {return res;})完全沒必要btw, return f(); 就夠了 您甚至可以將當前代碼進一步簡化為:

Promise.all(a.map(f)).then(result => console.log(result));

我看,當你有一個return (something)then ,另一個則必須附

這與.then無關。 .then簡單地返回一個承諾。 訪問 promise 的結果 ,您需要通過.then附加處理程序。

你不需要在這里這樣做,因為你將承諾傳遞給Promise.all 您正在通過.then((result)=>{console.log(result)})訪問結果。

為什么我不需要另一個附加到{return res;}這里?

我讀到當你在一個內部有一個return (something) ,另一個then必須附加,但這不是這里的情況。 救命?

還有另一種.then()附連到Promise.all() 你的意思是.catch()應該附加以避免Uncaught (in promise)

另請注意, Promise.all()不會從g()調用return ,以進一步鏈接Promise

.then().catch()內鏈.map()回調可以用於任一處理錯誤或拒絕Promise並返回一個解決Promise.then()鏈接到Promise.all() ; 或者throw當前或新的Error() Promise.all()調用。

該模式也可用於返回傳遞給所有的承諾.map()無論是解決或拒絕了.then()沒有立即調用.catch()鏈接到Promise.all()

 function f (index) { return new Promise(function (resolve, reject) { if (index !== 4) resolve(4); else reject("err at index " + index) }) } var a =[1, 2, 3, 4, 5]; function g () { return Promise.all(a.map((member, index)=>{ return f(index).then((res) => {return res;}) .catch(e => {console.log(e); throw new Error(e)}) })) .then((result)=>{console.log(result); return result}) .catch(e => { // handle error here, return resolved `Promise`, // or `throw new Error(e)` to propagate error to // `.catch()` chained to `g()` call console.log("handle error within g", e); return "error " + e.message + " handled"}); } g() .then(data => {console.log(data) /* `error err at 4 handled` */ }) .catch(e => console.log("done", e)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM