2017-06-26 87 views
-1

我在理解承諾方面遇到了一些問題。您能否幫助我:如何獲得承諾的結果?

我正在嘗試使用node-geocoder庫。

所以,這是一個函數,它應該返回Google地圖上某個點的緯度和經度的數組。

import NodeGeocoder from 'node-geocoder' 

export default function getLocation() { 
    const geocoder = NodeGeocoder({ 
     provider: 'google', 
    }) 

    const point = geocoder.geocode('29 champs elysée paris', (error, response) => { 
     return [response[0].latitude, response[0].longitude] 
    }) 

    return point 
} 

上面的代碼應該爲這個測試是確定:

import getLocation from './index' 

test('This is a test',() => { 
    expect(getLocation()).toEqual([48.8698679, 2.3072976]) 
}) 

測試失敗,我收到以下錯誤信息:

Expected value to equal: 
    [48.8698679, 2.3072976] 
Received: 
    {"fulfillmentValue": undefined, "isFulfilled": false, "isRejected": false, "rejectionReason": undefined} 
+0

如何打開尚未送達的包裹? Promise就像發貨確認一樣,只是您正在等待的東西的佔位符。你所能做的就是用這件事,等待承諾兌現/包裹交付。 '然後()'你可以隨心所欲地做任何事。 – Thomas

回答

-1

承諾.. 。 最好的!

對我來說,很難把握,一旦得到了,我就明白了。

閱讀評論,我用它們來描述承諾,而不是承諾中的代碼。

這裏是一個很好的例子。

function logIn(email, password) { 
 
    const data = { 
 
    email, 
 
    password 
 
    }; 
 

 
    // first I define my promise in a const 
 
    const AUTH = new Promise((resolve, reject) => { 
 
    // this is a normal Jquery ajax call 
 
    $.ajax({ 
 
     url: "/api/authenticate", 
 
     type: "POST", 
 
     data, // es6 
 
     success: function(res) { 
 
     resolve(res); // this will be sent to AUTH.then() 
 
     }, 
 
     error: function(err) { 
 
     reject(err); // this will be sent to AUTH.catch() 
 
     } 
 
    }) 
 
    }); 
 

 
    // once the resolve callback is sent back, I can chain my steps like this 
 
    AUTH.then((res) => { 
 
     let token = JSON.stringify(res); 
 
     return token; 
 
    }) 
 
    .then((token) => { 
 
     var d = new Date(); 
 
     d.setTime(d.getTime() + (1 * 24 * 60 * 60 * 1000)); 
 
     var expires = "expires=" + d.toUTCString(); 
 
     return document.cookie = `token=${token}; ${expires}; path=/`; 
 
    }) 
 
    .then(() => { 
 
     return window.location = "/"; // go home 
 
    }) 
 
    .catch(errCallback); // skips to this if reject() callback is triggered 
 
} 
 

 
function errCallback(err) { 
 
    return console.error(err); 
 
}