gpt4 book ai didi

javascript - 以非阻塞调用 JavaScript 的方式调用 API

转载 作者:行者123 更新时间:2023-12-03 01:18:38 25 4
gpt4 key购买 nike

我正在构建一个类似于待办事项列表的功能,当在输入任务字段上按 Enter 时,该功能会添加任务。 Enter 调用 API(添加任务),执行时间大约为 200 毫秒。由于这是阻塞调用,它会阻碍我的代码完全执行并影响系统的可用性。这是我想要实现的目标的代码示例。

handleChange(事件){

          if (e.key === 'Enter') {

targetTaskId = e.target.getAttribute("data-downlink")
this.props.addTask(this.props.currentProject.id, '', '', taskId, this.props.currentTasks) //this function calls an add Task API which halts my system momentarily

targetSelector = targetTaskId
$('#' + targetSelector).focus()
this.setState({activeTask: targetSelector})
highlightActiveComponent(targetTaskId)

}

}

//添加任务

   export function addTask (project_id, taskName, taskNotes, upLink, taskList) {
console.log('Add Task API call', project_id, taskName, taskNotes, upLink)
return (dispatch) => {
callApi('tasks?projectId=' + project_id + '&name=' + taskName + '&notes=' + taskNotes + '&upLink=' + upLink, 'post')
.then(res => {
console.log('Response new task ', res)
let newTask = {name: res.name, id: res.id, notes: res.notes, upLink: upLink, projectId: project_id, assignee: 0, completed: 0, tags: [], isLiked: false, stories: [], likes: [], downLink: res.downLink}
let newTaskList = addTaskToTaskList(taskList, upLink, newTask)
dispatch(updateTasks({currentTasks: newTaskList}))
dispatch({ type: 'SET_ACTIVE_TASK_ID', payload: res.id })

})
}
}

//获取

export const API_URL = 'https://clients.rohan.axcelmedia.ca/v1'

export default function callApi (endpoint, method = 'get', body) {
let headers = {
'Accept': 'application/json',
'Content-Type' : 'application/json'
}

if (auth.loggedIn()) {
headers = _.merge(headers, {
Authorization: `Bearer ${auth.getToken()}`
})
}
return fetch(`${API_URL}/${endpoint}`, {
headers,
method,
body: JSON.stringify(body)
}).then(response => {

return response
}).then(response => response.json().then(json => ({ json, response })))
.then(({ json, response }) => {
if (!response.ok) {
return Promise.reject(json)
}
return json
})
.then(
response => response,
error => error
)
}

将任务添加到任务列表

    export function addTaskToTaskList(tasks, upLink, newTask){
updateTaskDownLink(tasks, newTask.upLink, newTask.id)
updateTaskUpLink(tasks, newTask.downLink, newTask.id)
if(upLink == 0){
tasks.unshift(newTask)
// console.log("Added in the start", tasks)
return JSON.parse(JSON.stringify(tasks))
}
let myIndex = getIndexOfTaskById(tasks, upLink)
console.log("Added the new task from helper", myIndex)
if (myIndex) {
console.log("Added the new task")
tasks.splice(myIndex + 1, 0, newTask);
// console.log("New Task List", JSON.parse(JSON.stringify(tasks)))
}

return JSON.parse(JSON.stringify(tasks))
}

export function updateTaskUpLink(tasks, taskId, upLink){
tasks.forEach(function(element, index) {
if(element.id == taskId) { element.upLink = upLink }
});

return tasks
}

export function updateTaskDownLink(tasks, taskId, downLink){
tasks.forEach(function(element, index) {
if(element.id == taskId) { element.downLink = downLink }
});

return tasks
}

我的问题是,是否有办法以非阻塞方式调用此 API,以便我的代码继续执行,并且当收到来自 api 的响应时,我的光标以无缝方式移动到新任务。任何帮助,将不胜感激。谢谢[编辑]:添加了获取函数来演示异步调用

最佳答案

您应该使用 Fetch API 之类的方法以非阻塞方式调用 API:

fetch("/api/v1/endpoint/5/", {
method: "get",
credentials: "same-origin",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log("Data is ok", data);
}).catch(function(ex) {
console.log("parsing failed", ex);
});

console.log("Ciao!");

仅当服务器返回某些数据时,才会执行代码片段中显示数据的代码。

这意味着在我的示例中日志“Ciao!”将在“Data is ok: ...”之前显示

希望这有帮助:)

代码片段的来源:https://gist.github.com/marteinn/3785ff3c1a3745ae955c

关于javascript - 以非阻塞调用 JavaScript 的方式调用 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51866996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com