【问题标题】:I don't get the result of my promise despite using await尽管使用了等待,但我没有得到我的承诺的结果
【发布时间】:2020-05-14 07:14:17
【问题描述】:

我的函数如下所示:

async function getPlaceForecast(lat, long) {
//var response;
var day5forecast = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + lat + '&lon=' + long + '&appid=' + apikey;
try {
    const request = new Request(tmp2, {
        method: 'get'
    })
    let response = await fetch(request)
        .then(value => {
            console.log("than", value.json());
            return value//.json();
        })
        .catch(function (error) {
            console.error(error);
        });
}
catch{

}
//return response;

}

这是结果:

'than', { _40: 0, _65: 0, _55: null, _72: null }

这是不使用 .json() 的结果:

'than', { type: 'default',
status: 200,
ok: true,
   statusText: undefined,
  headers:
   { map:
     { 'access-control-allow-methods': 'GET, POST',
       'access-control-allow-credentials': 'true',
        'access-control-allow-origin': '*',
        'x-cache-key': '/data/2.5/forecast?lat=28.35&lon=-14.05',
        connection: 'keep-alive',
       'content-length': '14383',
      'content-type': 'application/json; charset=utf-8',
         server: 'openresty' } },
  url: 'http://api.openweathermap.org/data/2.5/forecast?lat=28.349414&lon=-14.046311&appid=<mykey>',
  _bodyInit:
    { _data:
     { size: 14383,
       offset: 0,
   blobId: '2dbf82c5-5d28-47db-9034-7f239bf8290a' } },
  _bodyBlob:
   { _data:
      { size: 14383,
       offset: 0,
        blobId: '2dbf82c5-5d28-47db-9034-7f239bf8290a' } } }

我做错了什么?

【问题讨论】:

  • url变量“day5forecast”在哪里使用?

标签: javascript android ios react-native request


【解决方案1】:

您正在记录 json() 返回的承诺,而不是承诺的履行值。

以下是您执行该功能的方法:

async function getPlaceForecast(lat, long) {
    const day5forecast = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + lat + '&lon=' + long + '&appid=' + apikey;

    const request = new Request(tmp2, {
//                              ^^^^−−−−−−−−− Should this be `day5forecast` ??
//                                           `day5forecast` isn't used otherwise...
        method: 'get'
    })
    let response = await fetch(request);
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    return response.json();
}

注意我已经删除了try/catches。留给调用者处理,以便他们知道getPlaceForecast 是成功还是失败。

您可能想知道末尾缺少await (return response.json();)。你不需要它,因为async 函数总是返回一个promise。 return response.json();async 函数的promise 解析为json() 返回的promise(因此它将根据json() 的promise 发生的情况而实现或拒绝)。你可以在那里拥有await (return await response.json();),它是无害的,¹但你不需要它。


¹ 具体来说:A)由于 ES2019 的变化,它在现代浏览器中完全无害;在理论发生变化之前,整体履行/拒绝被一个额外的异步“滴答”延迟(如果返回的承诺不是本机承诺,这种情况仍然会发生); B) 它大部分是无害的,即使有额外的勾号。 :-)

【讨论】:

    猜你喜欢
    • 2021-02-02
    • 2023-03-23
    • 2019-06-30
    • 2020-03-05
    • 2016-08-22
    • 1970-01-01
    • 2017-06-24
    • 2017-05-25
    • 2016-03-19
    相关资源
    最近更新 更多