سلام دوستان من میخوام از متد fetch که برای ارسال درخواست به سرور استفاده میشه رو به صورت await استفاده کنم ولی این خطا رو بهم میده
error: bundling failed: SyntaxError: C:UsersamirDesktopmyapp ode_modules eact-nativescriptssrcApp.js: await is a reserved word (48:21)
کد من:
try { const response = await fetch('http://192.168.1.103:8000/api/articles'); const responseJson = await response.json(); console.log(responseJson); } catch(error){ console.error(error); }
ممنون میشم راهنمایی کنید.
نه async نزاشتم که فهمیدم برای این خطا رو میده و یه سوال دیگه داشتم:
میخوام یک کلاس برای برای درخواست های http درست کنم که هی تو پروژه نگم fetch که کد ها طولانی بشه و میخوام یک تابع برای post درست کنم که اطلاعات json رو برگردونه ولی من هرکار میکنم promise برمیگردونه!
و از await استفاده کردم که باز هم نشد.
آیا راهی هست؟؟؟
کد کلاس api.js
class api{ url = 'http://192.168.1.103:8000/api/' method = ''; response = {}; constructor(method){ this.method = method; } static method(method){ return new this(method); } get(params = {}){ return fetch(this.url+this.method+this.makeQuery(params)) .then((response) => response.json()) .catch( (error) =>{ console.log(error) } ) } post(params = {}){ return this.request('post', params); } put(params = {}){ return this.request('put', params); } delete(params = {}){ return this.request('delete', params); } request(method, params = {}){ return fetch(this.url+this.method, { method: method, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(params), }) .then((response) => response.json()) .catch( (error) =>{ console.log(error) } ) } makeQuery(params){ let query = '?'; if(Object.keys(params).length){ Object.keys(params).forEach(key =>{ query += key + '=' + params[key] + '&'; }); } return query; } } export default api;
کد استفاده شده:
api.method('login') .post({ username: username, password: password }) .then(response =>{ console.log(response); });
ولی میخوام به این صورت باشه:
let response = api.method('login') .post({ username: username, password: password }); console.log(response);
آیا راهی وجود داره؟ و یا اینکه چی؟؟
آیا مایل به ارسال نوتیفیکیشن و اخبار از طرف راکت هستید ؟