2016-07-06 60 views
-3

中返回可迭代的解決方案我不僅希望返回此Promise的結果,還要返回它所調用的迭代器urlurls是一組網址。在Promise.all

function findMainLink(urls) { 
    return Promise.all(urls.map((url) => { 
    var result = nightmare 
    .goto(url) 
    .wait('#main') 
    .evaluate(function() { 
     return document.querySelector('#main a').href; 
    }); 

    nightmare.end() 
    return result 
    } 
} 

vo(findMainLink)([ 
'https://yahoo.com', 
'https://google.com' 
]) 
.then(res => console.log(res)) 
.catch(e => console.error(e)) 

當我做return {result,url}它不能解決,而是讓我回來的承諾的當前狀態。我將如何在結果中包含url?

+0

我在處理npm包噩夢的承諾,我想同時訪問網站,因此承諾。我想包括與噩夢功能被稱爲 – warg

+0

的網址,並且...有什麼與您發佈的代碼完全相關? –

+0

你真的應該向我們展示你的實際代碼,而不是一些簡單的例子,它幾乎沒有匹配。 – Bergi

回答

2

你想要的是

function findMainLink(urls) { 
    return Promise.all(urls.map((url) => { 
    var result = nightmare 
     .goto(url) 
     .wait('#main') 
     .evaluate(function() { 
     return document.querySelector('#main a').href; 
     }); 

    nightmare.end(); 
    return result; 
    }) 
    .then(results => results.map((result, i) => ({result, url[i]})); 
} 

傳遞的元組的數組當然Promise.all將無法​​工作,因爲一個元組是不是一個承諾,Promise.all有沒有辦法知道它應該往裏tuple 。相反,上面的代碼等待所有的解決承諾,然後映射結果給你你的元組數組(並返回一個承諾)。

+0

嗯,是的,這將工作。我正在考慮做'return result.then(result => {result,url})',但兩者都會同樣的結果 –

+0

要麼是好的,你的可能會有點乾淨。小的語法註釋,需要'result =>({result,url})'。 – 2016-07-06 18:38:04

+0

謝謝這工作:) – warg