javascript - Callback func as parameter in fetch - Stack Overflow

I'm trying to pass in a callback function as an argument to fetch. But i dont know how to run the

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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745428998a4627309.html

相关推荐

  • javascript - Callback func as parameter in fetch - Stack Overflow

    I'm trying to pass in a callback function as an argument to fetch. But i dont know how to run the

    11小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信