如何使用window .fetch加载本地json数据(ES6)

时间:2016-03-23 01:43:05

标签: javascript json promise webpack fetch-api

我有一个JSON对象(agendaItemsJson),我使用ES6语法加载(通过webpack使用json-loader)。使用以下命令会产生错误,因为fetch正在尝试解析URL,而agendaItemsJson是一个对象。

所以我的问题是我怎样才能正确模仿这个,以便我能够使用promise并让agendaItemsJson成为我的回应。

'use strict';

import BaseService from './base-service';
import agendaItemsJson from '../json/agenda.json';

class _AgendaService extends BaseService {

    getAgenda() {
        // TODO: Will use API instead of the JSON here under.
        return this.fetch(agendaItemsJson)
            .then(response => response);
    }
...

2 个答案:

答案 0 :(得分:2)

你能不能只返回使用agendaItemsJson解决的承诺? I.E使用ES6承诺?您甚至可以使用setTimeout推迟响应以模拟网络延迟。

getAgenda(){
    return new Promise(function(resolve){
        setTimeout(function(){
            resolve(agendaItemsJson);
        }, 1000);
    });
}

答案 1 :(得分:1)

如果agendaItemsJson是您想要使用承诺作为响应的对象,您可以这样做:

Manager

这比创建新Promise短,它会立即解析值。

顺便说一句,你不必等待执行超时。