我有一个JSON对象(agendaItemsJson),我使用ES6语法(通过webpack使用JSON加载程序)加载它。使用以下内容会出现错误,因为fetch正在尝试解析URL,而agendaItemsJson是一个对象。
所以我的问题是,我如何才能正确地模仿这一点,以便我能够使用承诺并得到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);
}
...
您能不能只返回一个由您的agendaItemsJson解决的承诺?I.E使用ES6承诺?您甚至可以使用setTimeout来延迟响应,以模拟网络延迟。
getAgenda(){
return new Promise(function(resolve){
setTimeout(function(){
resolve(agendaItemsJson);
}, 1000);
});
}
如果agendaItemsJson是您想要使用promise作为响应的对象,您可以这样做:
return Promise.resolve(agendaItemsJson);
这比创建一个新的Promise更短,它将立即解决价值。
顺便说一句,你不必等待超时执行。