2016-12-31 95 views
3
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;}這裏?承諾的NodeJS分辨率

我讀到,當你有一個return (something)在一個然後,另一個then必須附加,但它不是這裏的情況。幫幫我?

+1

的承諾將弄清楚,如果你打算地圖,或者flatMap。所以你可以返回一個普通的值,它會映射;返回一個承諾,它會flatMap。 – elclanrs

回答

3

Promise.all預計承諾的陣列。 .then返回一個承諾。因此,您的映射邏輯會將一組數字轉換爲一組承諾,正是您所需要的。

.then((res) => {return res;})是完全沒有必要順便說一句,return f();就足夠了。你甚至可以進一步簡化當前的代碼:

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

我讀到,當你有一個return (something)一個then內,另一個則必須連接

這有什麼好做.then.then只是返回一個承諾。要訪問的承諾的結果你需要通過.then附加的處理程序。

你並不需要,因爲你正在過承諾Promise.all做到這一點在這裏。您可通過訪問.then((result)=>{console.log(result)})結果

+0

爲什麼在「地圖(f)」中忽略了「返回」? – user7361276

+0

因爲'(member)=> {return f();}'在你的例子中等價於'f'。或者更一般的:給定'function foo(){};函數bar(){return foo(); }'然後調用'bar()'和直接調用'foo()'完全一樣。在你的例子中,不需要中間函數'(member)=> {return f();}',你可以直接將'f'傳遞給'a.map'。 –

0

爲什麼我不需要另一個然後附加到{return res;}在這裏?

我讀到,當你有一個return (something)在一個然後,另一個 then必須附加,但它不是這裏的情況。幫幫我?

還有另一個.then()附於Promise.all()。你是否應該附加.catch()以避免Uncaught (in promise)

還請注意,Promise.all()不是return編號從g()調用,以進一步鏈接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));