繁体   English   中英

返回JavaScript Promise拒绝的实现值

[英]Return JavaScript Promise rejected fulfilled value

我正在尝试使用node-geocoder npm包来获取某些对象位置的纬度和经度。

您能帮我理解JavaScript的承诺吗?

这是示例代码:

import nodeGeocoder from 'node-geocoder'

function getLocation (str) {
    // Selecting Google as provider
    const geocoder = nodeGeocoder({
        provider: 'google',
    })

    return geocoder.geocode(str)
        .then(response => {
            // I want to return latitude an longitude
            return [response[0].latitude, response[0].longitude]
        })
        .catch(error => {
            console.log(`Geocoder Error: ${ error }`)
        })
}

export default getLocation

所以。 这是一个测试(Jest框架):

import getLocation from './index'

test('Checking', () => {
    expect(getLocation('29 champs elysée paris')).toEqual([48.8698679, 2.3072976])
})

当我尝试使用此测试时,我只会得到承诺状态{"fulfillmentValue": undefined, "isFulfilled": false, "isRejected": false, "rejectionReason": undefined}

但是我需要得到承诺解决的结果。 我该怎么做?

我不想编辑测试

对于测试,大多数测试套件都会为您所有基于诺言的测试提供异步回调。 我希望它(双关语旨在)像这样工作:

import getLocation from './index'

test('Checking', (done) => {
  getLocation('29 champs elysée paris').then(geoData => {
    expect(geoData).toEqual([48.8698679, 2.3072976]);
    done();
  }).catch(error => {
    done(error)
  });
});

根据您可能使用的测试框架,调用解析器回调(即: done() )的方式可以改变。 但是,模式应大致相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM