2017-12-14 8 views
-1

가져 오기 위해 콜백 함수를 인수로 전달하려고합니다. 하지만 나는 index.js에서 콜백 자체를 실행하는 방법을 모르는 경우 api.js에서 가져 오기가 완료되었습니다.불러 오기에서 매개 변수로 콜백 func

하는 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; 
+0

함수는 항상'()'으로 호출됩니다. 나는. '콜백()'. –

답변

1

당신 .then()에 콜백 함수를 호출 할 수 있습니다? 약속을 되찾고 그 약속을 지키도록 노력하십시오. 이것이 약속 (및 가져 오기 API)에 관한 것입니다.

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

POST 요청입니다. 나는 그들이 어떤 데이터를 다시 얻을 필요가 있다고 생각하지 않는다. – Li357

+0

바로. 나는 어떤 데이터를 다시 얻지 못한다. 단지 콜백을 실행하여 게시물이 게시되었음을 나타낼 수있다. – user2952238

+0

"Api.post(). then (콜백 ({do something})));" ? – user2952238

0

당신은 단순히 then 콜백의 콜백 호출 할 수 있습니다

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

를하거나 체인 :

fetch(request) 
    .then(function() { 
    console.log(request); 
    }).then(callback); 
0 당신이 그렇게 할 이유

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

을 ...하지만 :