我如何从async-await返回拒绝?

问题描述 投票:2回答:1

当获取请求失败时,我想返回被拒绝。我怎么能拒绝异步等待?

class FetchUrl {
  static async getJson(api) {
    try {
        const response = await fetch(api);
        if (response.ok) {
            const questions = await response.json();
            return questions;
        }
    } catch (error) {
        throw new Error("Request Failed!");
    }
  }
}

 FetchUrl.getJson(this.api).then((resolved) => {
        console.log(resolved)
// this sampe of code is executing even fetch is rejected.. what can i do 
to avoid it?
    }, rejected => {
        console.log(rejected)
    })
}
async-await fetch
1个回答
0
投票

According to jQuery docs你应该使用类似的符号(这主要来自jQuery文档):

$.getJSON( this.api)
    .done(function( json ) {
    console.log( "JSON Data: " + json.users[ 3 ].name );
  })
  .fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Request Failed: " + err );
});
© www.soinside.com 2019 - 2024. All rights reserved.