javascript - 回调函数作为 fetch 中的参数

标签 javascript ecmascript-6 fetch

我正在尝试传递回调函数作为获取的参数。但我不知道当 api.js 中的 fetch 完成时如何从 index.js 运行回调本身。

index.js

import Api from './Api'
Api.post(callback)

API.js

class Api {
  constructor () {}
  static post(callback) {
    let url 'dummy';
    let data = {
      id: 2
    }

    let request = new Request(url, {
      method: 'POST',
      body: data,
      header: new Headers()
    })

    fetch(request)
      .then(function() {
        console.log(request);
      })
  }
}

export default Api;

最佳答案

可以.then()中调用回调函数:

class Api {
  static post (callback) {
    const request = /* ... */;
    fetch(request)
      .then(response => response.json())
      .then(result => callback(result)); // if you have a result
  }
}

...但是你为什么要这么做呢?尝试返回一个 promise 并履行该 promise 。这就是 Promise(以及 fetch API)的意义所在。

class Api {
  static post () {
    const request = /* ... */;
    return fetch(request)
      .then(response => response.json());
  }
}
// usage: 
Api.post().then(callback);

关于javascript - 回调函数作为 fetch 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47814924/

相关文章:

javascript - Three.js OrbitControls enableRotate/Pan = false 似乎不起作用

javascript - 父组件和子组件之间的 2 种方式事件绑定(bind)不起作用

javascript - 在 react-admin 中,当我使用 fetch 获取数据时,如何更新当前 View ?

javascript - javascript中 "click"事件的嵌套函数调用

javascript - 使用 process.hrtime() 的执行时间返回 vaSTLy 不同的结果

javascript - 如何访问响应数组中的promiseValue?

javascript - 每次渲染react时刷新组件状态

javascript - 地名自动完成城市/州,返回完整的州名而不是缩写

Javascript 匹配以从 URL 中删除部分文件名 - 替换最后一次出现

javascript - 您能否将您的博客设置为仅显示 Blogger 中帖子的第一个标签?