I've copied this from async.c