如何处理在异步函数之间共享的变量拼接?

时间:2021-01-20 23:22:30

I'm worried about a splice in one of my async functions causing another function to throw an error in a situation like this:

我担心我的一个异步函数的拼接会导致另一个函数在这种情况下抛出错误:

var sharedObject = [{key: 'foo', value: {varA: 1, varB: 5}}]

readObject: function(key) { 
    var index = findIndex(sharedObject, key)            <- line 4
    var b = sharedObject[index].value.varB              <- line 5
}

spliceObject: function(key) {
    var index = findIndex(sharedObject, key)
    sharedObject.splice(index,1)                        <- line 10
}

If the readObject and spliceObject functions are called asynchronously, and line 10 executes right in between line 4 and line 5, will line 5 throw an error because that entry in the object doesn't exist anymore?

如果readObject和spliceObject函数被异步调用,并且第10行在第4行和第5行之间执行,那么第5行会因为对象中的条目不再存在而抛出错误吗?

Or am I missing something with how async functions execute?

或者,我是否在异步函数的执行过程中漏掉了什么?

1 个解决方案

#1


3  

What you're worried about is (thankfully) impossible due to Javascript's single-threaded nature. Asynchronous code - including async functions and setTimeouts, will only run once the stack is clear. So, an ongoing thread will not be interrupted by something else asynchronous - the current thread must terminate before the next one starts.

值得庆幸的是,由于Javascript的单线程特性,您所担心的是不可能的。异步代码——包括异步函数和setTimeouts,只有在堆栈清除之后才会运行。因此,一个正在运行的线程不会被其他异步事件中断——当前线程必须在下一个线程开始之前终止。

#1


3  

What you're worried about is (thankfully) impossible due to Javascript's single-threaded nature. Asynchronous code - including async functions and setTimeouts, will only run once the stack is clear. So, an ongoing thread will not be interrupted by something else asynchronous - the current thread must terminate before the next one starts.

值得庆幸的是,由于Javascript的单线程特性,您所担心的是不可能的。异步代码——包括异步函数和setTimeouts,只有在堆栈清除之后才会运行。因此,一个正在运行的线程不会被其他异步事件中断——当前线程必须在下一个线程开始之前终止。