admin管理员组

文章数量:1430432

I'm trying to pass in a callback function as an argument to fetch. But i dont know how to run the callback itself from index.js when fetch is plete in api.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;

I'm trying to pass in a callback function as an argument to fetch. But i dont know how to run the callback itself from index.js when fetch is plete in api.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;
Share Improve this question edited Dec 14, 2017 at 13:53 SALEH 1,5621 gold badge14 silver badges22 bronze badges asked Dec 14, 2017 at 13:48 user2952238user2952238 7872 gold badges14 silver badges37 bronze badges 1
  • Functions are always called with (). I.e. callback(). – Felix Kling Commented Dec 14, 2017 at 15:05
Add a ment  | 

2 Answers 2

Reset to default 4

You can call your callback function in a .then():

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

... but why would you do that? Try to return a promise and work with that promise. This is what promises (and the fetch API) are about.

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

You can simply call the callback in the then callback:

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

Or chain it:

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

本文标签: javascriptCallback func as parameter in fetchStack Overflow